Member-only story
Asynchronous programming is pivotal to JavaScript, yet promises and callbacks can quickly lead to callback hell spaghetti code. Fortunately, ES6 generators and the yield keyword provide a clean solution for writing async code that is easy to read and maintain.
Let’s unravel generators and see how they greatly simplify async flow.
What are JavaScript Generators?
Generators are special functions that can be paused and resumed on demand. They work by using the new yield keyword to pause execution, and next() method to resume.
Here is a basic counter generator:
function* counter() {
let count = 0;
while (true) {
yield count++;
}
}
const generator = counter();
console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
We initialize a generator object from the generator function. On the first next()
call, execution pauses on the first yield expression, returning the yielded value. Subsequent next()
calls resume from where it left off, allowing us to control the execution.