In the last article, we introduced Promises. Once a Promise is executed, it cannot be suspended or canceled, so ES6 introduced Generator functions. You can suspend the execution of a function using the yield keyword, and you can change the execution flow.

What is a Generator function?

The Generator is primarily used for asynchronous programming and is used to encapsulate asynchronous tasks. It is a container for asynchronous tasks and allows functions to be executed or paused at a specified time.

Use grammar:

function *name(){

.

yield; // Add yield when you need to pause

.

yield;

.

}

const p = name();

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

P.next () // Execution starts at the last yeild and ends at the next yield

Generator is distinguished from a normal function

> defines a function with an extra * sign than a normal function.

2 When the Generator is called, it is called directly after the normal function name with parentheses. The Generator does not execute, nor does it return the result of the function. Instead, it returns a pointer object to the internal state. Each time next is called, the pointer executes from where it last stopped to the next yield.

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

Examples of generators are as follows:

function *show(){ console.log('1') yield; console.log('2') } const p = show(); p.next(); // Before the first yield, print 1 p.next(); // Execute the content after yield and print 2

> can pass a parameter, but only one parameter

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

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}

You can also add a return 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}

The return method

The return method returns the given value and finishes iterating through the generator function.

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

Generator function advantages

The Generator function is an asynchronous programming solution provided by ES6 that addresses two major problems:

  • The callback hell
  • Asynchronous flow control