Last active
September 11, 2019 15:42
-
-
Save erodozer/505b8d5c8121424e917b9ea3096dfce5 to your computer and use it in GitHub Desktop.
Promisify EventEmitter. For awaiting one time events, such as being notified if something is ready
This file contains hidden or 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
/** | |
* Create a one-time use Promise invoked by an event emitter | |
* Allows for awaiting an event | |
*/ | |
const asyncEvent = (eventEmitter, eventName) => | |
new Promise(resolve => { | |
const resolveFn = (...args) => { | |
// remove the listener so the promise is never resolved multiple times | |
eventEmitter.removeListener(eventName, resolveFn); | |
resolve(args); | |
}; | |
eventEmitter.on(eventName, resolveFn); | |
}) | |
module.exports = asyncEvent; |
This file contains hidden or 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 asyncEvent = require('async-event'); | |
async function start() { | |
const emitter = new EventEmitter(); | |
setTimeout(() => emitter.emit('say', 'World'), 1000); | |
console.log(`[${Date.now()}] Hello`); | |
const [who] = await asyncEvent(emitter, 'say'); | |
console.log(`[${Date.now()}] ${who}`); | |
} | |
start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment