0

Run below sample, you will see setTimeout callbacks always are executed later than Promise callback. Are there any mechanisms causes this result? or this is not ture?

setTimeout(function() {
  console.log(1)
}, 0)

new Promise(function (resolve, reject) {
  resolve(2)
}).then(console.log)

setTimeout(function() {
  console.log(3)
}, 0)

new Promise(function (resolve, reject) {
  resolve(4)
}).then(console.log)

console.log('rush...')
Sphinx
  • 10,519
  • 2
  • 27
  • 45
  • Have a look at [this great response](https://stackoverflow.com/questions/24117267/nodejs-settimeoutfn-0-vs-setimmediatefn) on stackoverflow – Baboo Aug 24 '18 at 23:44
  • 1
    Related: [Promise vs setTimeout](https://stackoverflow.com/questions/38752620/promise-vs-settimeout), [What is the order of execution in javascript promises](https://stackoverflow.com/questions/36870467/what-is-the-order-of-execution-in-javascript-promises) – Jonathan Lonowski Aug 24 '18 at 23:44

2 Answers2

3

Native promises are scheduled as a microtask. When the current execution stack finishes, microtasks are run first, and regular tasks will happen after.

For more information on the event loop, including information on microtasks, i recommend this presentation: https://www.youtube.com/watch?v=cCOL7MC4Pl0 . The section on microtasks begins at 24 minutes in.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • this video is awesome. it is worth watching it frame by frame. – Sphinx Aug 25 '18 at 00:14
  • Just found [HTML SPEC: event loop processing model](https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model) describes the details as well. – Sphinx Aug 25 '18 at 00:40
0

this is normal because Javascript is single-threaded and considering how did you wrote the code your Promises are executed in a synchronous way (while the script is been loaded) while the setTimeout are asynchronous (after the script have been loaded).