Why does Promise.then 'onFulfilled' functi

2019-02-25 04:55发布

问题:

This question already has an answer here:

  • Is setTimeout with no delay the same as executing the function instantly? 3 answers
  • What is the difference between “event loop queue” and “job queue”? 3 answers
  • Promise.then Job execution order 3 answers

Can someone explain why the promise 'then' function fires before the setTimeout function? I would have thought the setTimeout function would be scheduled on the event loop first, so it would run before the promise.then function.

setTimeout(() => {
    console.log('timer done, thought this would print second')
}, 0)

Promise.resolve().then(() => {
    console.log('promise done, thought this would print third')
})

console.log('synchronous, should print first')

Output:

'synchronous, should print first'

'promise done, thought this would print third'

'timer done, thought this would print second'