Created
March 23, 2019 10:09
-
-
Save yuta0801/fee28a9c5460a5bc2c08a805d5cb645e to your computer and use it in GitHub Desktop.
Generatorify 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
// Referred to https://raw.githubusercontent.com/denoland/deno_std/v0.3.2/http/server.ts | |
function deferred() { | |
let resolve, reject | |
const promise = new Promise((res, rej) => { | |
resolve = res | |
reject = rej | |
}) | |
return { | |
promise, | |
resolve, | |
reject | |
} | |
} | |
async function* listen(emitter, event) { | |
const env = { | |
queue: [], | |
deferred: deferred() | |
} | |
emitter.on(event, (...args) => { | |
env.queue.push(args) | |
env.deferred.resolve() | |
}) | |
while (true) { | |
await env.deferred.promise | |
env.deferred = deferred() | |
const queueToProcess = env.queue | |
env.queue = [] | |
for (const result of queueToProcess) { | |
yield result | |
env.deferred.resolve() | |
} | |
} | |
} | |
function generatorify(emitter) { | |
return event => listen(emitter, event) | |
} | |
module.exports = generatorify |
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 emitter = new (require('events')) | |
const generatorify = require('./generatorify') | |
// emitter.on('eventName', (arg1, arg2) => { | |
// console.log(arg1, arg2) | |
// }) | |
!(async () => { | |
const listen = generatorify(emitter) | |
for await (const [arg1, arg2] of listen('eventName')) { | |
console.log(arg1, arg2) | |
} | |
})() | |
emitter.emit('eventName', 1, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment