开始学习发电机,我遇到以下脚本。

我对first next()感到困惑,为什么没有为第一个next()打印console.log。

function* callee() {
    console.log('callee: ' + (yield));
}
function* caller() {
    while (true) {
        yield* callee();
    }
}
> let callerObj = caller();

> callerObj.next() // start
{ value: undefined, done: false }
// why console.log is not returning 'callee' ??

> callerObj.next('a')
callee: a
{ value: undefined, done: false }

> callerObj.next('b')
callee: b
{ value: undefined, done: false }

最佳答案

当您有一个生成器时,它将在暂停阶段启动,并且第一个next调用将生成器运行到第一个屈服点。每次从子生成器“屈服”时。如果将日志记录添加到两个函数的入口点,您将看到以下内容:

function* callee() {
  console.log('Callee is running up to the first yield point');
  console.log('callee: ' + (yield));
}
function* caller() {
  console.log('Caller is running up to the first yield point');
  while (true) {
    yield* callee();
  }
}

当使用测试代码运行此实现时,您将看到:
> let t = caller()
> t.next()
Caller is running up to the first yield point
Callee is running up to the first yield point
Object {value: undefined, done: false}

10-06 04:02