假设我们有以下生成器函数:
function* testGenerator() {const result = yield Promise.resolve('foobar').then(res => res);console.log(result);}
如果我使用以下行运行此生成器,它会记录 undefined
const test = testGenerator();
test.next();
test.next();
Run Code Online (Sandbox Code Playgroud)
但在传奇中,这样的线路会记录下来foobar.我只是好奇这背后的机制是什么(将yield的结果赋给变量)
编辑:
TL; DR:
使用参数调用next()方法将恢复生成器函数执行,替换使用next()中的参数暂停执行的yield语句
基本上,要使其记录"foobar",只需将第一个yield的值传递给第二个yield,这样当它恢复时,yield语句将替换为值:
function* testGenerator() {
const result = yield Promise.resolve('foobar');
console.log(result);
}
const test = testGenerator();
test.next().value.then(r => test.next(r))
Run Code Online (Sandbox Code Playgroud)