Generators are a powerful feature in JavaScript that allow you to pause and resume the execution of a function, and to yield values back to the caller. They are particularly useful for creating iterators and for implementing asynchronous operations.
What is a Generator?
A generator is a function that can be paused and resumed, allowing you to control the flow of execution. When a generator function is called, it doesn't execute its code immediately. Instead, it returns a special object, known as a generator object, which can be used to control the execution of the function.
Syntax
To create a generator function, you use the function*
syntax:
function* generatorFunction() {
// Generator code here
}
Example
Here's a simple example of a generator function that yields numbers from 1 to 5:
function* generateNumbers() {
for (let i = 1; i <= 5; i++) {
yield i;
}
}
const gen = generateNumbers();
for (let num of gen) {
console.log(num); // Outputs: 1, 2, 3, 4, 5
}
Using Generators with Async/Await
Generators can be used in conjunction with the async/await
syntax to create asynchronous iterators. This allows you to write asynchronous code that looks and behaves like synchronous code.
Example
Here's an example of a generator function that fetches data from a server and yields the results:
async function* fetchData() {
const data = await fetch('https://api.example.com/data');
const result = await data.json();
for (const item of result) {
yield item;
}
}
const dataGen = fetchData();
for (let item of dataGen) {
console.log(item); // Outputs the fetched data
}
Conclusion
Generators are a powerful feature in JavaScript that can be used for a variety of purposes, from creating iterators to implementing asynchronous operations. By understanding how generators work, you can write more efficient and maintainable code.
For more information on generators, check out our JavaScript Generators Guide.