Combine Promise and EventEmitter
// you can use default eventemitter or using third part library, checkout about eventemitter3 in npm
const { EventEmitter } = require('eventemitter3')
const reusify = require('reusify')
/**
* @description Create owner custom costructor for inhertitance event emitter data
*/
function EventDriven() {
/**
* @description Inheritance all event core method from EventEmitter to reusify Function
*/
this.reusify = reusify(EventEmitter).get()
Object.defineProperties(this.reusify, {
nextTick: {
value: process.nextTick,
writable: true,
enumerable: true
},
parse: {
value: JSON.parse,
writable: true,
enumerable: true
},
stringify: {
value: JSON.stringify,
writable: true,
enumerable: true
},
promise: {
value: Promise,
writable: true,
enumerable: true
},
eventName: {
value: undefined,
writable: true,
enumerable: true
},
data: {
value: undefined,
writable: true,
enumerable: true
},
response: {
value: undefined,
writable: true,
enumerable: true
}
})
}
EventDriven.prototype.pub = function (eventName, data) {
this.reusify.eventName = eventName
this.reusify.data = data
if (this.reusify.data !== undefined) {
this.reusify.nextTick(() => this.reusify.emit(this.reusify.eventName, this.reusify.stringify({ data: this.reusify.data })))
return Promise.resolve(this.reusify)
}
}
EventDriven.prototype.sub = function (eventName) {
let self = this
self.reusify.response = new self.reusify.promise(function (resolve, reject) {
self.reusify.eventName = eventName
self.reusify.on(self.reusify.eventName, function (data) {
self.reusify.data = data
self.reusify.response = self.reusify.parse(self.reusify.data)
resolve(self.reusify.response.data)
})
if (self.reusify.response !== (undefined && null)) {
/**
* @description after success unsubscribe event name
*/
self.reusify.nextTick(() => self.reusify.off(self.reusify.eventName))
/**
* @description after subscribe success reset property value
*/
self.reusify.nextTick(() => {
self.reusify.eventName = undefined
self.reusify.data = undefined
self.reusify.response = undefined
})
}
})
return self.reusify.response
}
exports.event = new EventDriven()