3

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'

user3692823
  • 341
  • 1
  • 11
  • 3
    If it were all synchronous, we wouldn't it print the 'promise done' before the 'synchronous, should print first' ? – user3692823 Mar 15 '17 at 03:06
  • 1
    Good question! Answer: they're not scheduled on the same event queue, the event loop will run promise callbacks before other callbacks – Bergi Mar 15 '17 at 03:11

0 Answers0