Created
May 30, 2018 19:26
-
-
Save bhurlow/a9daf0fe5e23e8f250914b4ae399c94a to your computer and use it in GitHub Desktop.
async iteratros with buffer limit
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
function chan(n) { | |
let internalQueue = [] | |
let drain = null | |
async function* wrappedIterator() { | |
while (true) { | |
if (internalQueue.length) { | |
if (drain) drain() | |
yield internalQueue.shift() | |
} | |
} | |
} | |
function write(data) { | |
return new Promise((resolve, reject) => { | |
if (internalQueue.length <= 5) { | |
internalQueue.push(data) | |
return resolve() | |
} | |
if (internalQueue.length >= 5) { | |
drain = () => { | |
internalQueue.push(data) | |
drain = null | |
resolve() | |
} | |
} | |
}) | |
} | |
return { values: wrappedIterator, write } | |
} | |
async function main() { | |
let count = 0 | |
let c = chan(5) | |
async function doWrite() { | |
await c.write({ data: `ITEM-${count++}` }) | |
doWrite() | |
} | |
doWrite() | |
process.stdin.resume() | |
process.stdin.setRawMode(true) | |
process.stdin.on('data', async x => { | |
let val = await c.values().next() | |
console.log(val) | |
}) | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment