Member-only story

Discover JavaScript Generators for Easier Asynchronous Coding

An Introduction to Generator Functions and Yielding Asynchronous Control Flow

Max N
2 min readJan 17, 2024

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.

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet