await 的执行顺序在节点中没有意义

问题描述 投票:0回答:1

我想了解异步 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 已执行。

有人可以向我解释一下吗?为什么异步函数有时会被扔到事件循环中,有时却不会?我是这样预测的,什么时候?

如果去掉await,顺序是1 2 3 4 5。

我只是想了解这里的逻辑是什么。

编辑: 如果await关键字是关键,为什么会导致相同的执行顺序?

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
javascript node.js async-await
1个回答
0
投票

async
函数始终同步执行,直到第一个
await
。当等待的 Promise 解决时,执行继续。
async
函数始终返回 Promise,即使其中没有
await
。即使 Promise 是同步
resolve(…)
的,它的结算也总是推迟到工作中。

© www.soinside.com 2019 - 2024. All rights reserved.