JavaScript - Generators
JavaScript generators are a powerful function technique available to JavaScript developers. Generators let developers write asynchronous functions in a cleaner, more structured way. But what are generators, actually?
A generator is a special function that lets the developer return values step by step instead of returning them all at once. Generators can also be used to create iterators. A function defined as a generator can return multiple values by using the "yield" keyword.
Here is an example that shows how to create a simple generator in JavaScript:
function* idGenerator() {
let id = 0;
while(true) {
yield id++;
}
}
let gen = idGenerator();
console.log(gen.next().value); // Output: 0
console.log(gen.next().value); // Output: 1
console.log(gen.next().value); // Output: 2
In this example a generator function "idGenerator" is defined. It contains a while loop that runs forever and returns an ID on each iteration, incremented by 1. The value of the ID is returned using the "yield" keyword. We initialize an instance of this generator function with "let gen = idGenerator()" and then print three IDs by calling "console.log(gen.next().value)" three times.
The output of the code above will be "0", "1" and "2".
Generators can also support asynchronous functions by using "yield" to pause the code and wait for the result of an asynchronous operation before executing the next line. Here is an example that shows how to create an asynchronous generator in JavaScript:
function* asyncIdGenerator() {
let id = 0;
while(true) {
yield fetch('https://jsonplaceholder.typicode.com/todos/' + id)
.then(response => response.json())
.then(data => data.id);
id++;
}
}
let gen = asyncIdGenerator();
gen.next().value.then(val => console.log(val)); // Output: 1
gen.next().value.then(val => console.log(val)); // Output: 2
In this example a generator function is used in the same way as "idGenerator", but instead of simply incrementing the ID, an asynchronous function fetches data from an API and returns the ID from the response. The "fetch" method is used to retrieve the data, and the "yield" keyword is used to pause the execution of the generator function until the asynchronous operation has completed. We initialize an instance of this generator function with "let gen = asyncIdGenerator()" and then print two IDs by calling "gen.next().value.then(val => console.log(val))" twice. The output of the code above will be "1" and "2".