Skip to content

Instantly share code, notes, and snippets.

@bhurlow
Created May 30, 2018 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhurlow/a9daf0fe5e23e8f250914b4ae399c94a to your computer and use it in GitHub Desktop.
Save bhurlow/a9daf0fe5e23e8f250914b4ae399c94a to your computer and use it in GitHub Desktop.
async iteratros with buffer limit
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