Skip to content

Instantly share code, notes, and snippets.

@ForbesLindesay
Forked from nanot1m/iter.js
Last active October 20, 2017 18:11
Show Gist options
  • Save ForbesLindesay/40b670872eeffc2b867762000d5900df to your computer and use it in GitHub Desktop.
Save ForbesLindesay/40b670872eeffc2b867762000d5900df 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