0 day streak
javascript / intermediate
Snippet

Custom Async Iterators for API Pagination

Async generators allow you to create custom iterators that produce values asynchronously. Using yield* with an array inside the loop allows you to flatten the paginated results, providing a seamless for-await-of loop for the consumer of the data.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
async function* fetchUserPages(baseUrl) {
let page = 1;
while (true) {
const response = await fetch(`${baseUrl}?page=${page}`);
const data = await response.json();
if (data.users.length === 0) break;
yield* data.users;
page++;
}
}
// Usage:
for await (const user of fetchUserPages('https://api.example.com/v1')) {
console.log(user.name);
}
nodejs
Breakdown
1
async function* fetchUserPages(baseUrl)
Defines an asynchronous generator function.
2
yield* data.users;
Delegates iteration to each individual element of the fetched users array.