yield关键字如何在JavaScript ES6生成器中真正起作用?

时间:2018-04-17 12:47:59

标签: javascript ecmascript-6 iterator generator

我在ES6中处理生成器,我想从概念上理解下面函数中发生的事情:

function* createNames() {
    const people = [];

    people.push(yield);
    people.push(yield);
    people.push(yield);

    return people;
}

const iterator = createNames();
iterator.next('Brian');
iterator.next('Paul');
iterator.next('John');
iterator.next(); // output: ["Paul", "John", undefined]

我的问题是:为什么第一次推动会被忽略?数组不应该像people = ['Brian', 'John', 'Paul', undefined]那样吗?抱歉这个愚蠢的问题,但我真的很想能够完全掌握这一点。提前谢谢!

1 个答案:

答案 0 :(得分:3)

调用createNames()不会执行生成器内部的任何代码。它创建一个迭代器的实例,并在第一次next()调用时开始执行。

const iterator = createNames(); 
// Iterator instance created, but hasn't executed yet.

iterator.next('Brian');
// creates the people array
// attempts to push, yields
iterator.next('Paul');
// pushes 'Paul'
// attempts to push, yields
iterator.next('John');
// pushes 'John'
// attempts to push, yeilds
iterator.next(); 
// pushes undefined
// returns ["Paul", "John", undefined]