javascript / intermediate
Snippet
Efficient Resource Loading with Async Generators
Async generators allow you to iterate over data that is fetched asynchronously. This 'lazy loading' approach saves memory by only keeping one page of data in memory at a time during processing.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
async function* fetchPages(limit) {let page = 1;while (page <= limit) {const response = await fetch(`https://api.example.com/items?page=${page}`);const data = await response.json();yield data.items;page++;}}for await (const items of fetchPages(3)) {console.log('Processed batch of size:', items.length);}
nodejs
Breakdown
1
async function* fetchPages
Declares an asynchronous generator function.
2
yield data.items
Pauses execution and returns the current batch to the caller.
3
for await (const items of ...)
Iterates over each yielded promise-wrapped value sequentially.