Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active January 29, 2026 09:24
Show Gist options
  • Select an option

  • Save WebReflection/b83cf5822ca70b667c615c9c3548bb8c to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/b83cf5822ca70b667c615c9c3548bb8c to your computer and use it in GitHub Desktop.
Refillable Generators: The Better Alternative

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?

A class based approach

The current idea has been formalized as gen-q module

Tests

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);
//   }
// }());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment