【发布时间】:2017-02-28 09:06:48
【问题描述】:
假设我们有以下生成器函数:
function* testGenerator() {
const result = yield Promise.resolve('foobar')<del>.then(res => res);</del>
console.log(result);
}
如果我使用以下行运行此生成器,它会记录 undefined
const test = testGenerator();
test.next();
test.next();
但在传奇中,这样的行将记录foobar。我只是好奇这背后的机制是什么(将yield的结果分配给变量)
编辑:
TL;DR:
使用参数调用 next() 方法将恢复生成器 函数执行,替换执行所在的 yield 语句 暂停了来自 next() 的参数
基本上,要让它记录“foobar”,只需将第一个yield的值传递给第二个next,这样当它恢复时,yield语句被替换为值:
function* testGenerator() {
const result = yield Promise.resolve('foobar');
console.log(result);
}
const test = testGenerator();
test.next().value.then(r => test.next(r))
【问题讨论】:
-
yield返回传递给next()的任何内容。你什么都没通过。
标签: javascript ecmascript-6 redux redux-saga