generator生成器函数

generator生成器函数

定义:

  • function后面加了*
  • 函数体里有 yield关键字
1
2
3
4
5
function* Hello(name) {
    yield `hello${name}`;
    yield `how are you`;
    yield `bye`;
}

  

表现形式

  • 调用这个函数,不会立即执行函数体里的内容,返回一个对象
  • 通过这个对象的next方法,可以驱动函数的执行,但是并不会执行完,执行到下一个yield关键字的时候,停住
  • 调用next()方法返回的结果
    • value: yield关键字后面的表达式的结果。
    • done:函数是否执行完。 (当函数return的时候执行完,返回true)
    • 函数return的时候,value是return的内容,done是true
1
2
3
4
5
6
7
8
9
let ite = Hello('前端君');
console.log(ite)//[object  Hello]
 
console.log(ite.next());//{value: "hello前端军",done: false}
 
console.log(ite.next());//{value: "how are you",done: false}
 
console.log(ite.next());
console.log(ite.next());//{value: undefined,done: true}

  

  • next()方法可以加参数
    • next(参数)
    • 这个参数会作为上一个yield关键字的返回值

作用

  • 函数可以返回多个值
  • 在调用函数之后,可以给函数体里传递数据了
  • 调用函数的时候,可以控制函数内部的执行了
  • 可以解决异步问题

生成器函数的执行器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 写一个generator函数的执行器
        function run(gen) {
            // 编写一段递归调用来执行我们的代码
            let lt = gen;//这里调用,上面let就不要调用
             
            // debugger
            return new Promise((reslove, reject) => {
                // {value,done}
                function step(data) {
                    if (data.done) {
                        console.log("递归调用结束了");
                        reslove(data.value)
                    } else {
                        data.value.then(res => {
                            console.log(res);
                            step(lt.next(res))
                        })
                    }
                }
 
                step(lt.next())
            })
        }
        run(gen);

关键字‘yield*’;

作用:一个Generator函数里面调用另一个Generator函数使用yield*

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function* gen2(){
    yield "gen2 start";
    yield "gen2 end";
 
}
 
function* start(){
    yield "start";
    yield* gen2();
    yield "end";
}
 
var ite1 = start();
console.log(ite1.next());//start
console.log(ite1.next());//gen2 start
 
console.log(ite1.next());//gen2 end//执行函数时依次执行完
console.log(ite1.next());//end
console.log(ite1.next());//undefined

  

与普通函数的区别:

  1. 普通函数用function来声明,Generator函数用function*声明。

  2.Generator函数函数内部有新的关键字:yield( 产出),普通函数没有.

return与yield的区别:

    yield在这里起到了十分重要的作用,就相当于暂停执行并且返回信息。
    return代表的是终止执行,yield代表的是暂停执行
原文地址:https://www.cnblogs.com/chengxiao35/p/13610857.html