Last active
November 11, 2019 14:54
-
-
Save kena0ki/6a411bad64e9220ebcb856165ee91e0e to your computer and use it in GitHub Desktop.
reads and displays stdin line by line without using @@asyncIterator
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 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