In the previous article, “ES6 New Syntax (5) — A Detailed Description of Promises,” we introduced promises. Once a Promise has been executed, it cannot be paused or canceled. Therefore, ES6 introduces Generator functions, which can yield the keyword to suspend the execution of the function or alter the execution of the function.

What is a Generator function?

The Generator is mainly used for asynchronous programming and is used to encapsulate asynchronous tasks. It is a container for asynchronous tasks and allows functions to execute or pause at the specified time.

Use grammar:

function *name(){

.

yield; // Add yield when a pause is required

.

yield;

.

}

const p = name();

P.ext () // Calls the function and stops at the first yield

P.next () // Start from the previous yeild and end at the next yield

A Generator is different from an ordinary function

1> The function is defined with an extra star.

The Generator does not execute, nor does it return the result of the function’s run. Instead, it returns a pointer object to the internal state. The next() method of the iterator object must be called to move the pointer to the next state. Each time next is called, the pointer is executed from where it stopped before until the next yield.

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

Examples of generator are as follows:

function *show(){ console.log('1') yield; console.log('2') } const p = show(); p.next(); // Before the first yield is executed, print 1 p.ext (); // After the yield is executed, print 2Copy the code

Yield characteristics

1> 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)
Copy the code

2 > the 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}
Copy the code

Returns can also be added to generator functions

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}
Copy the code

The return method

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

The return method returns an argument if it is provided, or undefined if it is not.

Advantages of Generator functions

Generator functions are an asynchronous programming solution provided by ES6 that addresses two major problems:

  • The callback hell
  • Asynchronous flow control