跳到正文
当下的七炎
返回

认识Generator

编辑文章

示例1

const tgenerator = () => {
  function* gen(x) {
    var y = x * (yield "hello");
    yield 11;
    yield 22;
    console.log("x", x); //6
    console.log("y", y); //36

    return y;
  }
  // console.log(gen.__proto__);

  let gen1 = gen(6);
  // let res = gen1.next();
  console.log(gen1.next().value); // hello
  // let res2 = gen1.next(6);
  console.log(gen1.next(6).value); // 11,第二个yield的结果,并且把第一个yield的结果赋值为6
  console.log(gen1.next(3).value); //22
  console.log(gen1.next(3).value); //36
  // next参数是给上一个yield 传植
};

示例2,处理异步

function foo(x,y) {
    ajax(
        "http://some.url.1/?x=" + x + "&y=" + y,
        function(err,data){
            if (err) {
                // 向`*main()`中扔进一个错误
                it.throw( err );
            }
            else {
                // 使用收到的`data`来继续`*main()`
                it.next( data );
            }
        }
    );
}

function *main() {
    try {
        var text = yield foo( 11, 31 );
        console.log( text );
    }
    catch (err) {
        console.error( err );
    }
}

var it = main();

// 使一切开始运行!
it.next();

示例3,具体看一下异步处理

 function foo1(a) {
    setTimeout(() => {
      // 这个next必须是异步的,不然会有一个错误
      //Generator is already running
      gen1.next(2);
    }, 200);
  }
  function* gen(x) {
    var y = x * (yield foo1(44));
    return y;
  }
  let gen1 = gen(3);
  // 异步函数的next的值替换了yield foo1(44)的值
  console.log(gen1.next().value);//6,return的值

Generator


编辑文章
分享这篇文章:

评论

使用 GitHub 账号登录后即可评论


上一篇
script标签中defer和async
下一篇
Object.create做了什么?