New syntax in ES6 (6) — detailed explanation of generator function


In the previous article “ES6 new syntax (V) – promise details”, we introduced promise. Once promise is executed, it cannot be suspended or cancelled. Therefore, ES6 introduces the generator function. You can suspend the function execution process through the yield keyword and change the execution process.

What is the generator function?

Generator is mainly asynchronous programming. It is used to encapsulate asynchronous tasks. It is a container for asynchronous tasks. It can let functions execute or pause at the time we specify.

Use syntax:

function *name(){

yield; // Add yield when you need to pause



const p = name();

p. Next() / / call the function and stop at the first yield

p. Next() / / execute from the previous yield to the next yield

Difference between generator and ordinary function

1> When defining a function, there is an * sign more than an ordinary function.

2> When calling, the ordinary function name is directly called with parentheses, and the generator does not execute, and the return is not the function running result, but the pointer object pointing to the internal state. You must call the next () method of the ergodic object to move the pointer to the next state. Each time next is called, the pointer will execute from the last stop to the next yield.

3> Ordinary functions cannot be paused, but the generator function is executed in segments, yield is the pause flag, and next () can resume execution.

The generator instance is as follows:

function *show(){
const p = show();; // Print 1 before executing the first yield; // After executing yield, print 2

Yield features
1> Parameters can be passed. Only one parameter can be passed

function *chuancan(){
 let a = yield;
const gen = chuancan();

2> Return value

function *fanhui(){
 yield 55;
let fh = fanhui()
let res1 =
console.log(res1) //{value: 55, done: false}
let res2 =
console.log(res2) //{value: undefined, done: true}

Return can also be added to the generator function

function *show(){
 yield 55;
 return 89;
let gen = show();
let res1 =;
console.log(res1) //{value: 55, done: false}
let res2 =;
console.log(res2) //{value: 89, done: true}

Return method

The return method returns the given value and ends traversing the generator function.

The return method returns a parameter when it is provided, or undefined when it is not provided.

Generator function advantages

The generator function is an asynchronous programming solution provided by ES6, which solves two major problems:

  • Callback hell
  • Asynchronous flow control