工作中遇到一个执行顺序的问题,百思不得其解,把它提炼出来了
// 按顺序输出console
async function fn1() {
console.log("1");
fn2();
console.log("2");
}
async function fn2() {
console.log("3");
await fn3();
console.log("4");
}
function fn3() {
console.log("5");
return 1;
}
fn1() // 13524 (??? 问号脸,为什么2在4前面打印? )
重新理一下await,它在返回一个promise之后 后面的代码需要等待await后面的函数返回结果再执行,也就是说await后面的代码在微任务队列里面,所以
async function fn2() {
console.log("3");
// await fn3();
// console.log("4");
// 上面代码相当于
await fn3().then(()=> {
console.log("4");
});
}
唉~es6反复看反复忘