Generator function [JS]

In Javascript, once a function starts to execute, it will run to the end or end when it encounters a return. During the execution, no other code can interrupt it, and it cannot pass in values ​​from the outside to the function body.

The emergence of the Generator function (generator) makes it possible to break the complete operation of the function, and its grammatical behavior is completely different from that of the traditional function.

Generator is also an asynchronous programming solution. Its biggest feature is that it can hand over the execution right of the function. Generator function can be seen as a container for asynchronous tasks. The places that need to be paused are marked with yield syntax. The Generator function is generally used in conjunction with yield, and the Generator function returns an iterator at the end. If you don't know much about iterators, you can tutor this part by yourself.

Check out this experiment:

 

Other examples:

function* gen() {
    let a = yield 111;
    console.log(a);
    let b = yield 222;
    console.log(b);
    let c = yield 333;
    console.log(c);
    let d = yield 444;
    console.log(d);
}
// yield 表达式只能用在 Generator 函数里面,用在其它地方都会报错

let t = gen();
t.next(1); //第一次调用next函数时,传递的参数无效,故无打印结果
t.next(2); // a输出2;
t.next(3); // b输出3; 
t.next(4); // c输出4;
t.next(5); // d输出5;

Guess you like

Origin blog.csdn.net/qq_42533666/article/details/129217016