我目前正在探索 javascript 中 async/await 的概念。我知道 async 函数返回一个应该在将来解决的 promise ,它不会阻止代码的自然执行。这里我有一个代码我写的是为了测试 javascript 的异步执行。
console.log("1")
async function asyncFunc(){
for(i=0;i<10000000;i++){
}
console.log("3")
}
asyncFunc().then(()=>{console.log('4')});
console.log("2");
我除了代码将以下列方式执行:
first console.log() prints 1
secondly async function is called. As async code is non blocking,last console.log() will execute and thus prints 2 in the console.
After that console.log() inside async function will be executed and will print 3 in console.
lastly the promise will be resolved and console.log() inside
then
will be executed and prints 4.so expected output : 1,2,3,4
but in reality I get output as 1,3,2,4.
为什么它表现得像这样而不是我预期的方式
最佳答案
该函数在完成运行之前不会返回 promise (除非您等待
其中的另一个 promise )。
循环运行(阻塞一切),然后评估 console.log("3")
,然后它返回一个 promise 。
调用函数继续运行(记录 2)。
最后,释放事件循环并调用传递给 then
的函数。
将函数标记为异步不会将其中的同步代码转换为异步代码。
关于javascript - 异步函数中的代码在它后面的代码之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47836884/