关于async函数中await的执行分析
async函数中await命令后面是一个 Promise 对象。如果不是,会被转成一个立即resolve的 Promise 对象。那么await是否等待这个Promise置为resolve状态才能进行下一步运行呢?我们通过下面代码分析下
async function test(){
await new Promise(function(resolve,reject){
setTimeout(x=>resolve('11111'),2000);
}).then(x=>console.log(x));
await new Promise(function(resolve,reject){
setTimeout(x=>resolve('22222'),2000);
}).then(x=>console.log(x));
}
test()
//11111 2秒后打印
//22222 4秒后打印
分析得出await是在Promise的resolve状态下才进行下一步。
如果没有处理resolve状态呢?
async function test(){
await new Promise(function(resolve,reject){
//setTimeout(x=>resolve('11111'),2000);
});
await new Promise(function(resolve,reject){
setTimeout(x=>resolve('22222'),2000);
}).then(x=>console.log(x));
}
//测试发现并没有任何打印
所以await需要Promise的resolve状态。
那么reject状态又是如何呢?
async function test(){
await new Promise(function(resolve,reject){
setTimeout(x=>reject('11111'),2000);
}).catch(x=>console.log(x));
await new Promise(function(resolve,reject){
setTimeout(x=>resolve('22222'),2000);
}).then(x=>console.log(x));
}
//11111 2秒后打印
//22222 4秒后打印
async function test(){
await new Promise(function(resolve,reject){
setTimeout(x=>reject('11111'),2000);
});
await new Promise(function(resolve,reject){
setTimeout(x=>resolve('22222'),2000);
}).then(x=>console.log(x));
}
//报错
async function test(){
await new Promise(function(resolve,reject){
setTimeout(x=>reject('11111'),2000);
});
await new Promise(function(resolve,reject){
setTimeout(x=>resolve('22222'),2000);
}).then(x=>console.log(x));
}
test().catch(x=>console.log(x));
//11111 2秒后打印
分析得出:
1.如果await后面的promise拥有catch则不影响后续的执行
2.如果没有处理错误状态则会报错,如果test有错误处理则错误抛出给test的catch处理。
3.根据jQuery的promise机制分析猜测await的错误处理流程:如果await后面的Promise拥有错误处理函数,则将该函数放入错误处理队列,待抛出错误将处理函数和参数apply方法使用一下,如果没有错误处理函数,则从父级中查找错误处理函数放入队列,如果没有,再从上一级直到找到错误处理函数放入队列(这跟promise的catch用法符合),如果没有则报错。