Member-only story
JavaScript generators are an extremely useful, yet often overlooked feature for writing cleaner and more maintainable code. As an elegant alternative to callbacks and promises for handling asynchronous operations, generators provide a synchronous-looking syntax while abstracting away much of the complexity.
In this article, we’ll explore five practical use cases where JavaScript generators can help simplify your code.
Handle Asynchronous Operations with Ease
One of the most common applications for generators is to abstract asynchronous code to make it look synchronous. Instead of nesting callbacks or chaining promises, you can write straightforward procedural code.
Here’s a simple example fetching data from two endpoints:
function* fetchData() {
const data1 = yield fetch('/endpoint1');
const data2 = yield fetch('/endpoint2');
return { data1, data2 };
}
const it = fetchData();
it.next().value.then(data1 => {
it.next(data1).value.then(data2 => {
const result = it.next(data2);
console.log(result);
});
});