Generators normally iterate over a finite set and then complete, leaving the iterator done. Keeping a generator alive enables a replenishable FIFO queue by preventing completion and pausing when no items exist. Replacing the normal return with awaiting a promise lets the loop wait indefinitely for new items. Creating a new promise for each awaited item allows the generator to resume whenever external code pushes into the queue. Using while(true) inside the generator, combined with promise-based pauses, yields a simple API for processing items over time while allowing the queue to be refilled and resumed.
"Ever since writing about them, the generator in JavaScript has become my favorite hammer. I'll wield it nearly any chance I can get it. Usually, that looks like rolling through a finite batch of items over time. For example, doing something with a bunch of leap years: ...or lazily processing some files: In both examples, the pool of items is exhausted once and never replenished. The for loop stops, and the final item returned by the iterator contains done: true. C'est fini."
"That behavior makes sense - a generator wasn't designed to be resurrected after it's completed. It's a one-way street. But on at least one occasion, I've wanted it to be possible. Most recently, it happened while building a file upload tool for PicPerf. I wanted (read: demanded) to use a generator to power a replenishable, first-in-first-out (FIFO) queue. I did some tinkering, and liked where the effort ended up."
"First, a bit more on what I mean by "replenishable." A generator can't be turned on again, but we can get around that by holding it open when the queue of items becomes depleted. A great job for promises! Let's start with this setup: dots in a queue that are individually processed every 500ms. Here's our one-way queue: If we had a button for pushing items to the queue, and it were clicked after the generator had completed, nothing would happen."
Read at Alex MacArthur
Unable to calculate read time
Collection
[
|
...
]