一、当async中只有一个await时的执行顺序
下面是async函数中只有一个await时 的例子
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
二、当asyan中有多个await时的执行顺序
下面展示`当有多个await存在时的打印顺序
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
三、async同级有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
四、当含有setTimeout函数时:
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