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

Bru*_*zza 5 javascript iterator generator ecmascript-6

我正在处理ES6中的Generator,从概念上讲,我想了解以下函数中发生的情况:

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]
Run Code Online (Sandbox Code Playgroud)

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

thg*_*ell 4

调用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]
Run Code Online (Sandbox Code Playgroud)