【发布时间】: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 Promiseconstructor is not asynchronous。只有then回调是异步执行的。
标签: javascript node.js asynchronous promise event-loop