Last active
December 30, 2021 08:12
-
-
Save tracker1/987a389efa9e9ec632d1d5f6ea0d7772 to your computer and use it in GitHub Desktop.
Node Promise + EventEmitter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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