eventemitter to promise

Solutions on MaxInterview for eventemitter to promise by the best coders in the world

showing results for - "eventemitter to promise"
Eliott
31 Apr 2018
1const { EventEmitter } = require('eventemitter3')
2
3/**
4 * @description Create owner custom costructor for inhertitance event emitter data
5 */
6function EventDriven() {
7	this.resolves
8	this.rejects
9	EventEmitter.call(this)
10}
11
12/**
13 * @description Inheritance all event core method from EventEmitter to EventDriven Function
14 */
15util.inherits(EventDriven, EventEmitter)
16
17EventDriven.prototype.pub = function (eventName, data) {
18	const compress = $zlib.brotliCompressSync(JSON.stringify({ data }), {
19		chunkSize: 999999999,
20		maxOutputLength: 999999999
21	})
22
23	const decompress = $zlib.brotliDecompressSync(compress, {
24		chunkSize: 999999999,
25		maxOutputLength: 999999999
26	})
27
28	const promise = new Promise((resolve, reject) => {
29		this.resolves = resolve
30		this.rejects = reject
31	})
32
33	promise.emit = this.emit
34	promise.on = this.on
35
36	process.nextTick(() => this.emit(eventName, decompress.toString('utf-8')))
37	process.nextTick(() => this.off(eventName))
38	return this
39}
40
41EventDriven.prototype.sub = function (eventName) {
42	let self = this
43	return new Promise(function (resolve, reject) {
44		self.on(eventName, function (data) {
45			resolve(JSON.parse(data).data)
46		})
47	})
48}
49
50exports.event = new EventDriven()