-
-
Save ForbesLindesay/40b670872eeffc2b867762000d5900df to your computer and use it in GitHub Desktop.
Push iterator
This file contains 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 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