throw 方法
try,catch()捕獲內(nèi)部錯誤后,還會執(zhí)行一次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 提前結(jié)束
如果在try{}finally(){}語句中try{}里面return 那么就會推遲的finally結(jié)束
yield*語法
yield [1,2,3,4,5,6] 返回的時整個數(shù)組;
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函數(shù)不是構(gòu)造函數(shù),可以變通,既有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)=>{//執(zhí)行器
callNextStep(a)
function callNextStep(res) {
let result;
try { //防止generator函數(shù)拋出錯誤
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)
})