ES6:Generator函数(1)

Generator函数是ES6提供的一种异步编程解决方案。它会返回一个遍历器对象

function* helloWorldGenerator(){

      yield “hello”;

      yield “world”;

      return “ending”;

}
var hw = helloWorldGenerator();

hw.next();  //{value:”hello”,done:false}

hw.next(); //{value:”world”,done:false}

hw.next(); //{value:”ending”,done:true}

hw.next(); //{value:undefined,done:true}

*yield只能用在Generator函数中,用在普通函数中会报错

*yield表达式在使用在另一个表达式中时必须加括号console.log((yield))

用途:手动“惰性求职”(Lazy Evalution)

function* sumGenerator(){

    yield 123+345;

}

 

posted @ 2018-03-08 10:59  GuJinYu  阅读(176)  评论(0编辑  收藏  举报