es6 中的Generator

Generator函数是ES6提供的一种异步编程解决方案。通过yield标识位和next()方法调用,实现函数的分段执行。
1.Generator函数

  function* helloGenerator() {
       yield "hello";
       yield "generator";
       return;
   }
   var h = helloGenerator();
   console.log(h.next());//{ value: 'hello', done: false }
   console.log(h.next());//{ value: 'generator', done: false }
   console.log(h.next());//{ value: 'undefined', done: true }

1)创建了h对象,指向helloGenerator的句柄,

(2)第一次调用nex(),执行到"yield hello",暂缓执行,并返回了"hello"

(3)第二次调用next(),继续上一次的执行,执行到"yield generator",暂缓执行,并返回了"generator"。

(4)第三次调用next(),直接执行return,并返回done:true,表明结束。

经过上面的分析,yield实际就是暂缓执行的标示,每执行一次next(),相当于指针移动到下一个yield位置

2.next 传参


  function* gen(x,y){
   	  let z= yield x+y;
   	  let result = yield z*x;
   	  return result
   }
   var g = gen(5,6);
   var i =g.next();//{value: 11, done: false}
   g.next(i.value);//{value: 55, done: false}

3.return

  function* gen(x,y){
   	  yield 1;
   	  yield 2;
   	  yield 3;
   }
   var g = gen();
   g.next();//{value: 1, done: false}
   g.next();//{value: 2, done: false}
   g.return();//{value: undefined, done: true}
   g.next();//{value: undefined, done: true}

执行return()方法后就返回done:true,Generator 函数遍历终止,后面的yield 3不会再执行了

4.yield 表达式

  function* foo(){
   	yield "a";
   	yield "b";
   }
   function* gen(x,y){
   	  yield 1;
   	  yield 2;
   	  yield* foo();
   	  yield 3;
   }
   var g = gen();
   console.log(g.next());//{value: 1, done: false}
   console.log(g.next());//{value: 2, done: false}
   console.log(g.next());//{value: "a", done: true}
   console.log(g.next());//{value: "b", done: true}
   console.log(g.next());//{value: "3", done: true}

5.应用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值