ES6 yield (yield 1)(yield 2)(yield 3)()

ES6 yield (yield 1)(yield 2)(yield 3)()

function* generatorFunction() {
  yield (yield 1)(yield 2)(yield 3)();
}
var iterator = generatorFunction();

// [1, 2, 3]
var iteratedOver = [iterator.next().value, iterator.next().value, iterator.next().value];

我不确定这是怎么回事。

yield 不是 return 函数引用,那么像 (yield 2) 这样的括号语句是做什么的 - 它们是没有主体的粗箭头匿名函数吗?他们如何使用这样的部分应用程序来调用?

我在这里遗漏了一些东西,有人可以解释一下吗?


更新:试过三个浏览器,Chrome 50.0.2661.86、Safari 9.1 (50.0.2661.86)、Firefox 44.0.2,均正常运行。

ESFiddle 也执行无误。

评论者报告 Babel 执行也没有错误。

题目出自http://tddbin.com/#?kata=es6/language/generator/send-function,第二套

I'm not sure how this works.

呃,是的,它应该行不通。由于 Babel 中的错误,它才起作用。

yield doesn't return a function reference, so what are the parenthetical statements like (yield 2) doing - are they fat arrow anonymous functions without bodies? How are they called using partial application like that?

不,这真的只是标准函数应用,没有魔法。 yield 可以 return 一个函数引用,当它这样做时可能会起作用。如果没有,它将在第三次 .next() 调用时抛出异常。

作为工作版本的示例:

function* generatorFunction() {
  yield (yield 1)(yield 2)(yield 3)();
}
var test = (a) => {
  console.log(a);
  return (b) => {
    console.log(b);
    return (c) => {
      console.log(c);
      return 4;
    };
  };
};
var iterator = generatorFunction();
iterator.next(); // {value: 1, done: false}
iterator.next(test); // {value: 2, done: false}
iterator.next("a"); // "a" {value: 3, done: false}
iterator.next("b"); // "b" undefined {value: 4, done: false}
iterator.next("d"); // {value: undefined, done: true}

那么这是如何工作的呢?那些 nested/chained yield 语句最好写成

function* generatorFunction() {
  let fn1 = yield 1;
  let a = yield 2;
  let fn2 = fn1(a);
  let b = yield 3;
  let fn3 = fn2(b);
  let res = fn3();
  let d = yield res;
  return undefined;
}

Commenters report Babel executes without errors as well.

那是因为 babel 错误。如果你检查 transpiler output,它实际上表现得像

function* generatorFunction() {
  let fn1 = yield 1;
  let a = yield 2;
  let b = yield 3;
  // these are no more executed with only 3 `next` calls
  let fn2 = fn1(a);
  let fn3 = fn2(b);
  let res = fn3();
  let d = yield res;
  return undefined;
}