javascript - 异步函数中的代码在它后面的代码之前执行

标签 javascript asynchronous async-await

我目前正在探索 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/

相关文章:

c# - 我们需要在 Controller 中使用 async/await 关键字吗?

c# - 调用 Task.Result 时 Windows 窗体中断

javascript - 我如何突破 React 映射以显示具有两个值的对象,一个是数组,另一个是字符串或数字(结果)

c# - 从资源管理的角度来看,如何处理对 Task.Run 的多个请求?

node.js - Nodejs 错误 : Global connection already exists. 首先调用 sql.close()

c# - 如果缓冲区太小,是否可以防止异常?

node.js - process.nextTick() 是否立即执行

javascript - 使用带有字符串的另一个数组过滤带有对象的数组

可变作用域的 JavaScript 术语

javascript - 我如何检查一个函数的所有表单元素都不为空?