小编sun*_*uan的帖子

使用redux-saga时,为什么yield语句是执行的值而不是undefined?

假设我们有以下生成器函数:

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:

MDN功能*参考

使用参数调用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)

javascript ecmascript-6 redux redux-saga

1
推荐指数
1
解决办法
1282
查看次数

标签 统计

ecmascript-6 ×1

javascript ×1

redux ×1

redux-saga ×1