Stay up to date with AI tools, model releases, and developer workflows that matter.

Sources indicate that weekly. Free. One click to leave.

It has been revealed that 7 Day Free Trial. Cancel Anytime.

Most JavaScript code loads data first and processes it afterward. That works for a list of ten items, but it falls apart when the list has a million entries, never ends, or arrives one network page at a time. Generators and iterators offer another approach: produce values only when someone asks for them. This article explains the iteration protocol, shows how generators build on it, and finishes with async generators for paginated data.

An iterator is any object with a next() method. Each call returns an object with two properties: value, the next item, and done, a boolean that becomes true when the sequence ends. An iterable is an object that hands out an iterator through a method keyed by Symbol.iterator. Arrays, strings, Maps and Sets are all iterables, which is why for...of, spread syntax and destructuring work on them.

You can write the protocol by hand:.

Spread syntax calls [Symbol.iterator]() once, then calls next() until done is true. The code is correct but noisy. You manage the state yourself, and every new sequence needs the same scaffolding.

A generator function, declared with function*, returns an iterator without the manual bookkeeping. The yield keyword pauses the function and sends a value to the caller. The next call to next() resumes execution exactly where it stopped, with all local variables intact.

Recent findings suggest that calling countdown(3) does not run the body. It creates a generator object, and the body runs in slices as the consumer asks for values. Generator objects are iterable too, so spread and for...of work on them directly. The suspended state is the whole trick: the function body acts as a small state machine that the engine writes for you.

Values can also flow back in. The argument passed to next() becomes the result of the yield expression:.

The first call to next() only runs the generator up to its first yield, so any argument passed to it is ignored. That detail trips up many developers.

Laziness is where generators earn their place. Array methods such as map and filter process the whole array at each step and allocate a newly introduced array each time. A generator pipeline handles one item at a time through the entire chain, which makes it possible to work with sequences that have no end:.

It has been revealed that the naturals generator never finishes, yet the pipeline completes because take stops asking after four results. No array of squares is ever built, and no number beyond 49 is computed.

There is a useful cleanup rule here. When a for...of loop exits early, through break, return or a thrown error, it calls the iterator's return() method. For a generator, that runs any finally blocks and ends the sequence. In the pipeline above, finishing take releases the generators upstream as well, so a generator that holds a file handle or a database cursor can close it inside a finally block.

Real applications spend more time waiting than computing, and async generators bring the same lazy model to asynchronous work. Declare one with async function* and consume it with for await...of. Each iteration waits for a promise to settle before the loop body runs.

Sources indicate that A paginated API is a natural fit. Assume each response contains an items array and a nextUrl property that is null on the last page. This generator requests one page at a time and yields its items:.

The consumer decides how much to fetch:.

Sources indicate that once collectTitles has enough titles, the return statement ends the loop, which calls return() on the async generator. No further requests are made. Without a generator you would write a recursive function or a manual loop with its own stopping logic, and callers would have no say over the pace.

Async iteration also suits streams. In Node.js, readable streams are async iterable, so for await...of lets you process a large file chunk by chunk instead of holding all of it in memory.

Iterators define how to walk a sequence, generators make writing them painless, and async generators extend the same idea to data that arrives over time. Start small: replace one function that builds a large intermediate array with a generator, or one manual pagination loop with an async generator. The pull-based model keeps memory use predictable and gives the consumer control over how much work gets done.

It has been revealed that 7 Day Free Trial. Cancel Anytime.

โ†’ Read original article