本篇文章转载自我的个人博客
async function fn(){
//...
}
//等同于
function fn(args){
return spawn(function* (){
//...
});
}
所有async函数都可以写成第二种形式,其中spawn函数是自动执行器
spawn函数实现:
function spawn(genF){
return new Promise(function(resolve,reject){
var gen = genF();
function step(nextF){
try{
var next = nextF();
} catch(e){
return reject(e);
}
if(next.done){
return resolve(next.value);
}
Promise.resolve(next.value).then((v)=>{
step(()=>gen.next(v));
},(e)=>{
step(()=>gen.throw(e));
});
}
step(()=>{gen.next(undefined)});
});
}