This gist comes after my comment left in the original post.
The pattern is great but the way it was presented not too great:
- it's all about queue ownership
- the queue cannot iterate in multiple loops because it would create forever pending promises all over
- the queue is just an Array after all, so how about we treat it as such?
The current idea has been formalized as gen-q module
import Queue from 'https://esm.run/gen-q';
const numbers = new Queue(1, 2, 3);
(async function test() {
for await (const item of numbers) {
console.log(item);
}
console.log('done');
}());
setTimeout((...args) => {
// nobody will see these items
numbers.push(...args);
// drop all items from the queue
numbers.splice(0);
setTimeout(async function test() {
console.log('after reset');
numbers.push(...args);
for await (const item of numbers) {
console.log(item);
}
console.log('done');
}, 1000);
}, 1000, 4, 5, 6);
// Error caused by trying to iterate again
// (async function test() {
// for await (const item of numbers) {
// console.log(item);
// }
// }());