Skip to content

Instantly share code, notes, and snippets.

@tracker1

tracker1/future.js

Last active Feb 3, 2020
Embed
What would you like to do?
Node Promise + EventEmitter
module.exports = () => {
// break resolve and reject out of a promise
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
// return as a future
return {
promise,
resolve,
reject,
};
};
const { EventEmitter } = require('events');
const createFuture = require('./future');
/**
* PromiseEmitter class - Combines Promise and EventEmitter
* @param {*} fn is a funtion that should accept (resolve, reject, emitter)
*/
function PromiseEmitter(fn) {
const { resolve, reject, promise } = createFuture();
// add eventemitter to promise
Object.assign(promise, EventEmitter.prototype);
EventEmitter.call(promise);
// run fn call out of band
setTimeout(() => fn.call(promise, resolve, reject, promise), 1);
return promise;
}
module.exports = PromiseEmitter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment