gpt4 book ai didi

javascript - es6 生成器 while(true)

转载 作者:搜寻专家 更新时间:2023-11-01 05:21:16 24 4
gpt4 key购买 nike

开始学习生成器,我遇到了下面的脚本。

我对第一个 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}

关于javascript - es6 生成器 while(true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38528139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com