ES6 generator状态机要点记录

throw 方法

try,catch()捕获内部错误后,还会执行一次next()

var gen = function* gen(){
try {
yield console.log('a');
} catch (e) {
// ...
}
yield console.log('b');
yield console.log('c');
}
var g = gen();
g.next() // a
g.throw() // b
g.next() // c

return 提前结束

如果在try{}finally(){}语句中try{}里面return 那么就会推迟的finally结束

yield*语法

yield [1,2,3,4,5,6] 返回的时整个数组;
yield* [1,2,3,4,5,6] 返回123456(寻找遍历器)
yield 'hello' 返回的时整个字符串;
yield* [1,2,3,4,5,6] 返回单个字符(寻找遍历器)  

function* foo(){
    yield 2;
    yield 3;
    yield 'foo';//return 'foo';会有不同效果
}
function* bar(){
    yield 1;
    var v = yield *foo();
    console.log('v: '+v);
    return 4;
}
var it = bar();
console.log(it.next())
console.log(it.next())
console.log(it.next())
console.log(it.next())
console.log(it.next())

generator函数不是构造函数,可以变通,既有this属性,也有next方法

function* gen(){yield this.a = 1;}
function F(gen){return gen.call(gen.prototype)
var f = new F(gen)
f.next()
console.log(f)

async generator语法糖

  function gen(a){
    let gen = (function* (){
        var a = yield promise(22)
        console.log(a)
        var b = yield promise(44)
        console.log(b)
    })();

    return new Promise((resolve,reject)=>{//执行器
        callNextStep(a)
        function callNextStep(res) {
          let result;
          try {  //防止generator函数抛出错误
            Promise.resolve(res).then((data)=>{
                result = gen.next(data);
                next(result);
            }).catch(e=>{  //防止yield后面promise抛出错误
              return reject(e);
            })
          } catch (e) {
              return reject(e);
          }
        }
        function next({done,value}) {
            if(done){
                resolve(value)
            }else{
                callNextStep(value)
            }

        }
    })
}
gen().catch((e)=>{
    console.log('错误 ',e)
})

你可能感兴趣的:(ES6 generator状态机要点记录)