What Are Generators?
Generators are special functions that can be paused and resumed. They produce a sequence of values lazily (on demand).
Creating Generators
function* countTo(n) {
for (let i = 1; i <= n; i++) {
yield i;
}
}
const counter = countTo(3);
console.log(counter.next()); // { value: 1, done: false }
console.log(counter.next()); // { value: 2, done: false }
console.log(counter.next()); // { value: 3, done: false }
for (const num of countTo(5)) {
console.log(num); // 1, 2, 3, 4, 5
}
Async Generators
async function* fetchPages(url) {
let page = 1;
while (true) {
const response = await fetch(`${url}?page=${page}`);
const data = await response.json();
if (data.length === 0) break;
yield data;
page++;
}
}
for await (const page of fetchPages('https://api.example.com/posts')) {
console.log(`Processing ${page.length} posts`);
}
Chunk Generator Pattern
function* chunks(array, size) {
for (let i = 0; i < array.length; i += size) {
yield array.slice(i, i + size);
}
}
const batches = [...chunks([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)];
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]