Skip to content

Instantly share code, notes, and snippets.

@jleedev
Last active February 7, 2018 20:16
Show Gist options
  • Save jleedev/c5f5db135967f8e0796935af932d49d1 to your computer and use it in GitHub Desktop.
Save jleedev/c5f5db135967f8e0796935af932d49d1 to your computer and use it in GitHub Desktop.
event driven vs promise driven
'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();
~/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