我想知道异步js函数是在何时被附加到事件循环的,以及何时被立即执行:
async function test2(){
console.log('3 test2 is being executed');
}
async function test(){
console.log('2 test is being executed');
await test2();
console.log('4 test 2 was awaited');
}
console.log('1 test is about to be called');
test();
console.log('5 test was called');
最初,我假设无论一个函数是否有任何实际的异步函数(setTimeout、fetch、loadFile等)发生,如果该函数被声明为异步,它总是会被附加到事件循环中。
因此,根据该逻辑,控制台日志的顺序如下:
1 test is about to be called
5 test was called
2 test is being executed
3 test2 is being executed
4 test 2 was awaited
所以我假设,没有任何实际异步函数的异步函数总是会立即执行,导致以下顺序:
1 test is about to be called
2 test is being executed
3 test2 is being executed
4 test 2 was awaited
5 test was called
但我得到的却是:
1 test is about to be called
2 test is being executed
3 test2 is being executed
5 test was called
4 test 2 was awaited
这意味着执行顺序为:
测试被调用
测试正在立即执行(尽管标记为异步)
test2正在立即执行(与test相同)
在运行test2之后,控制权返回到第14行(这意味着事件循环一定做了什么)
最后,测试报告test2已执行。
有人能给我解释一下吗?为什么异步函数有时会被抛出到事件循环中,有时则不会?我这是可以预测的,什么时候?
此外,如果您删除wait,则顺序为1 2 3 4 5。
我只是想知道这里的逻辑是什么。
编辑:
如果wait关键字是关键,为什么这会导致相同的执行顺序?
async function test2(){
console.log('3 test2 is being executed');
}
async function test(){
console.log('2 test is being executed');
await test2();
console.log('4 test 2 was awaited');
}
console.log('1 test is about to be called');
let a=async ()=>{
await test();
}
a();
console.log('5 test was called');
1 test is about to be called
2 test is being executed
3 test2 is being executed
5 test was called
4 test 2 was awaited