Member-only story
Asynchronous programming is an essential part of modern web development. It allows us to perform tasks concurrently and improve the performance of our applications. One way to implement asynchronous programming in JavaScript is through generators.
This article will explore what generators are, how they work, and how we can use them to create efficient async code.
What are Generators?
In JavaScript, a generator function looks like a regular function, but with an asterisk (*) before its name. When called, it doesn’t return a single value; instead, it returns an iterator object known as a generator. The generator has a next()
method which you can call repeatedly to get new values from the generator function. Each time next()
is called, the generator resumes execution at the point where it left off, allowing you to pause and resume functions easily.
Here’s an example of a basic generator function:
function* myGeneratorFunction() {
yield 'Hello';
yield 'World';
}
const gen = myGeneratorFunction(); // Returns a generator object…