Last active
February 7, 2018 20:16
-
-
Save jleedev/c5f5db135967f8e0796935af932d49d1 to your computer and use it in GitHub Desktop.
event driven vs promise driven
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
v9.5.0 |
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
'use strict'; | |
const readline = require('readline'); | |
process.on('uncaughtException', err => {throw err}); | |
process.on('unhandledRejection', err => {throw err}); | |
async function* each_line(rl) { | |
let lines = []; | |
let unpark; | |
rl.on('line', line => { | |
lines.push(line); | |
if (unpark) { | |
unpark(); | |
} | |
}); | |
let CLOSED = Symbol('CLOSED'); | |
rl.on('close', () => { | |
lines.push(CLOSED); | |
if (unpark) { | |
unpark(); | |
} | |
}); | |
while (true) { | |
while (lines.length > 0) { | |
let next = lines.shift(); | |
if (next === CLOSED) { | |
return; | |
} else { | |
yield next; | |
} | |
} | |
await new Promise(resolve => { | |
unpark = resolve; | |
}); | |
} | |
} | |
async function main() { | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: null, | |
}); | |
for await (let line of each_line(rl)) { | |
console.log('line', line); | |
} | |
console.log('done'); | |
} | |
main(); |
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
~/junk/hello-async-generators$ printf '1\n2\n3\n' | node --harmony-async-iteration ./main.js | |
line 1 | |
line 2 | |
line 3 | |
done | |
~/junk/hello-async-generators$ node --harmony-async-iteration ./main.js | |
1 | |
line 1 | |
2 | |
line 2 | |
3 | |
line 3 | |
done | |
~/junk/hello-async-generators$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment