Javascript承诺setTimeout执行

我一直在玩Promises,但无法理解以下代码的状况:

const promise = new Promise((resolve, reject) => {
  console.log('Promise started')
  resolve('Success')
})

setTimeout(() => {
  console.log('Log inside first setTimeout')
}, 0)

promise.then(res => {
  console.log('Promise log after fulfilled ❌')
})

setTimeout(() => {
  console.log('Log inside second setTimeout')
}, 0)

输出为:

Promise started 
Promise log after fulfilled ❌ 
Log inside first setTimeout 
Log inside second setTimeout 

为什么不输出以下内容?

Promise started 
Log inside first setTimeout 
Log inside second setTimeout 
Promise log after fulfilled ❌ 

Between setTimeout(fn, 0)fn call and resolve()fn call which will be given priority?

是否取决于浏览器的实现细节?

评论
  • 柠檬心i
    柠檬心i 回复

    Because the setTimeout is pushed aside until the time has passed - even if it's "instant", it still pushes it to a different thread and resolves the promise before returning to see if it's finished or not. setTimeout(fn, 0) is lower in priority than resolve()/promise.then().

  • hrerum
    hrerum 回复

    承诺具有更高的优先级,因为它们在微任务队列中排队。