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

Time:2021-7-30

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

yield;

}

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(){
 console.log('1')
 yield;
 console.log('2')
}
const p = show();
p.next(); // Print 1 before executing the first yield
p.next(); // After executing yield, print 2

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

function *chuancan(){
 console.log('1')
 let a = yield;
 console.log('a',a)//12
}
const gen = chuancan();
gen.next()
gen.next(12)

2> Return value

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

Return can also be added to the generator function

function *show(){
 console.log('1')
 yield 55;
 console.log(2);
 return 89;
}
let gen = show();
let res1 = gen.next();
console.log(res1) //{value: 55, done: false}
let res2 = gen.next();
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