【问题标题】:microtask vs synchronous code execution order [duplicate]微任务与同步代码执行顺序[重复]
【发布时间】:2020-10-11 14:34:53
【问题描述】:

我试图了解事件循环中javascript异步代码的执行顺序。

这是我的非常短的代码 sn-p。

我们如何解释实际的执行顺序:in promise -> end -> in then?为什么promise构造函数在console.log('end')之前运行?

const p = new Promise((res, rej) => {
  console.log('in promise')
  res()
})

p.then(() => console.log('in then'))

console.log('end')

【问题讨论】:

  • 我们可以通过说then 回调是异步的来解释它,如果你听说过“微任务”和“事件循环”这两个术语,你大概已经知道了。您还想了解哪些信息?
  • @Bergi 很抱歉提出一个笨拙的问题。我无法理解的是为什么承诺(这是异步的)在最终的console.log 之前执行,而then-block 是在它之后执行的。
  • 没有。 The new Promise constructor is not asynchronous。只有then 回调是异步执行的。

标签: javascript node.js asynchronous promise event-loop


【解决方案1】:

在promise构造函数中运行的第一件事,注销“in promise”

运行的第二件事是p.then,设置一些代码以在将来运行。

要运行的是console.log('end');

您的代码现在已完成运行,因此执行返回到事件循环。 Promise 处于已解决状态,因此微任务运行并且.then 回调注销“in then”。

【讨论】:

  • 为什么promise构造函数在console.log之前运行?
  • 因为它在前面的一行。 Promise 构造函数是同步的(与所有构造函数一样)。以(res, rej) 开头的代码在构建承诺期间立即运行。
  • @Nickolas Tower 非常感谢!这正是我不明白的。
猜你喜欢
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
相关资源
最近更新 更多