In JavaScript, a generator is a special type of function that allows you to pause and resume its execution. Generators are defined using the function* syntax, and they are capable of producing a sequence of values lazily, one at a time. They are particularly useful for working with asynchronous code and creating iterable objects.
Let's assume you have a web application that fetches a large dataset of users from a remote API. Loading all users at once would be inefficient and slow. Instead, you can use a generator to paginate through the data, fetching a limited number of users at a time as needed.
Example:
async function* fetchUsers() {
let page = 1;
const perPage = 10; // Number of users per page
while (true) {
const response = await fetch(`https://api.example.com/users?page=${page}&per_page=${perPage}`);
const users = await response.json();
if (users.length === 0) {
// No more users to fetch
break;
}
for (const user of users) {
yield user;
}
page++;
}
}
// Usage:
const userGenerator = fetchUsers();(async () => {
for await (const user of userGenerator) {
console.log(`User: ${user.name}, Email: ${user.email}`);
}
})();