ES6发电机令人困惑

per*_*ai1 1 javascript generator ecmascript-6

我试图了解这是多么有效.我已经完全操纵了这个代码,但仍然不明白它是如何返回它的值.我从http://davidwalsh.name/es6-generators的教程中得到了这个

function *foo(x) {
  var y = 2 * (yield (x + 1));
  var z = yield (y / 3);
  return (x + y + z);
}

var it = foo( 5 );

// note: not sending anything into `next()` here
console.log( it.next() );       // { value:6, done:false }
console.log( it.next( 12 ) );   // { value:8, done:false }
console.log( it.next( 13 ) );   // { value:42, done:true }
Run Code Online (Sandbox Code Playgroud)

我似乎对第一个下一个()有一点把握,但接下来的两个让我感到困惑的是8和42的值.

希望有人可以帮助解释这一点,以便我可以尝试掌握并使用发电机进入下一阶段.

c-s*_*ile 5

生成器不仅仅是闭包的语法糖,试试这个:

  function foo(x) 
  {
    var step = 0;
    var y;
    var z;

    function next(p) {

      switch( step++ ) {
        case 0: return { done:false, value:x + 1 }; break;
        case 1: y = 2 * p; return { done:false, value:y / 3 }; break;
        case 2: z = p; return { done:true, value: x + y + z }; break;
        default: return;
      }
    }
    return {next:next};
  }    

  var it = foo( 5 );
  console.log( it.next() );       // { value:6, done:false }
  console.log( it.next( 12 ) );   // { value:8, done:false }
  console.log( it.next( 13 ) );   // { value:42, done:true }
Run Code Online (Sandbox Code Playgroud)