【问题标题】:ES6/ES2015 yield within closure in a function* [duplicate]ES6/ES2015在函数闭包内产生* [重复]
【发布时间】:2016-04-30 08:22:33
【问题描述】:

你能从闭包中屈服吗?

// I want the following to work but instead I get:
//   Uncaught SyntaxError: missing ) after argument list(…)

function* test() {
    yield 1;
    [2,3].map(x => yield x);
    yield 4;
}

var gen = test();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
console.log(gen.next().value); // 4

【问题讨论】:

  • 不,你不能。
  • 如果没有从生成器“内部”(无论定义如何)调用闭包,它会做什么?

标签: javascript ecmascript-6 yield


【解决方案1】:

您应该使用yield* 将控件传递给其他可迭代对象 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/yield*

您还尝试在您无法做到的非生成器函数中 yield。只需使用return

function* test() {
    yield 1;
    yield* [2,3].map((x) => {return x});
    yield 4;
}

var gen = test();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3 
console.log(gen.next().value); // 4

【讨论】:

  • 请注意,在这种情况下,map 将被急切地评估为数组,我想这不是 OP 的本意。
猜你喜欢
  • 2018-02-03
  • 2016-10-14
  • 2016-02-21
  • 2015-12-18
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
相关资源
最近更新 更多