Skip to content

Instantly share code, notes, and snippets.

@kena0ki
Last active November 11, 2019 14:54
Show Gist options
  • Save kena0ki/6a411bad64e9220ebcb856165ee91e0e to your computer and use it in GitHub Desktop.
Save kena0ki/6a411bad64e9220ebcb856165ee91e0e to your computer and use it in GitHub Desktop.
reads and displays stdin line by line without using @@asyncIterator
const rl = require('readline').createInterface({ input: process.stdin });
const first = { promise: Promise.resolve(), next: null };
const queue = [first];
function asyncReadLine(event, asyncCallback){
rl.on(event, async (...args) => {
queue.push({ promise: new Promise(resolve => void (queue[queue.length - 1].next = resolve)), next: null });
const promiseObj = queue.shift();
await promiseObj.promise;
await asyncCallback(...args);
promiseObj.next();
});
}
asyncReadLine('line', async line => {
await new Promise(res => setTimeout(() => res(), 1000)); // delaying 1s to confirm whether inputs are sequentially read.
console.log(line);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment