1. The order of execution when there is only one await in async
The following is an example when there is only one await in the async function
async function async1() {
console.log("start")
await async2();
console.log("async1 end")
}
async function async2(){
console.log("async2 start");
}
async1();
console.log("ending........")
打印结果:
start
async2 start
ending......
async1 end
Second, the execution order when there are multiple awaits in asyan
The following shows the printing order when there are multiple awaits
function doSometing() {
console.log("执行doSometing");
return "testSometing";
}
async function async2() {
console.log("执行Async2");
return Promise.resolve("hello async");
}
async function async1() {
console.log("async1 start...");
const v1 = await doSometing();//关键点1
console.log(v1);
const v2 = await async2();
console.log(v2);
console.log(v1, v2);
}
async1();
console.log("end......")
打印结果:
async1 start...
执行doSometing
end......
testSometing
执行Async2
hello async
testSometing hello async
Three, the execution order when async same level has new Promises
async function async1() {
console.log("start")
await async2();
console.log("async1 end")
}
async function async2(){
console.log("async2 start");
}
async1();
console.log("ending........")
new Promise(function(resolve){
console.log("Promise1")
resolve();
}).then(function (){
console.log("Promise1 end")
})
打印结果:
start
async2 start
ending......
Promise1
async1 end
Promise1 end
4. When the setTimeout function is included:
async function async1() {
console.log("start")
await async2();
console.log("async1 end")
}
async function async2(){
console.log("async2 start");
}
async1();
setTimeout(function(){
console.log("setTimeout 2")
},0)
new Promise(function(resolve){
console.log("Promise1")
resolve();
}).then(function (){
console.log("Promise1 end")
})
console.log("ending........")
打印结果:
start
async2 start
Promise1
ending......
async1 end
Promise1 end
setTimeout 2