Skip to content

Instantly share code, notes, and snippets.

@jozsefs
Forked from ForbesLindesay/iter.js
Created October 20, 2017 18:11
Show Gist options
  • Save jozsefs/9abe469a5e685c8d11130b655d0265b3 to your computer and use it in GitHub Desktop.
Save jozsefs/9abe469a5e685c8d11130b655d0265b3 to your computer and use it in GitHub Desktop.
Push iterator
const Queue = require('then-queue'); // async queue that doesn't care what order you call push and pop.
const queue = new Queue();
// push sends to the first waiting `pop` if available, otherwise it acts as a buffer
listenToNewMessages(message => queue.push(message));
async function* MessagesGenerator() {
try {
while (true) {
// pop takes the first item if available, otherwise it waits for an item to be available
yield await queue.pop();
}
}
}
const messages = MessagesGenerator()
for await (let message of messages)) {
// even if you do something async here, no messages are ignored. e.g.
await new Promise(resolve => setTimeout(resolve, 1000));
console.log(message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment