async/await
async/await 是Generator的语法糖。
Generator
function *generator(){
yield 1
yield 2
}
let G=generator();
let result1=G.next();
console.log(result1.value,result1.done);
let result2=G.next();
console.log(result2.value,result2.done);
let result3=G.next();
console.log(result3.value,result3.done)
通过将Generator函数和自动执行器结合,包装在一个函数里。并返回Promise对象
function run(gen){
return new Promise((resolve,reject)=>{
var g=gen();
function next(val){
let res;
try{
res=g.next(val);
}catch(e){
return reject(e);
}
if(res.done){
return resolve(res.value);
}
Promise.resolve(res.value).then(val=>{
console.log(val)
next(val);
},error=>{
g.throw(error)
})
}
next();
})
}
网友评论