The order of js Promise and setTimeout

new Promise((resolve, reject) => {
  resolve()
}).then(() => {
  console.log(1)
  new Promise((resolve, reject) => {
    resolve()
  }).then(() => {
    console.log(2)
  })
  setTimeout(() => { console.log(3) }, 0)
})

console.log(4)

setTimeout(() => { console.log(5) }, 0)

// 4
// 1
// 2
// 5
// 3

Why print 2 to 5 first? After the first macrotask queue execution, push out the function in Promise.then in microtask queue . After execution, shouldn"t you call setTimeout in macrotask queue ? Why the Promise in the. Then is executed first.

Jun.02,2021
There are two Promise callbacks in
microtask queue . You can only walk next macrotask queue


after running.
new Promise((resolve, reject) => {
  setTimeout(()=>{resolve()},100);
}).then(() => {
  console.log(1)
  new Promise((resolve, reject) => {
    resolve()
  }).then(() => {
    console.log(2)
  })
  setTimeout(() => { console.log(3) }, 0)
})

console.log(4)

setTimeout(() => { console.log(5) }, 0)

if you write 5 like this, it will definitely come before 2. Your code writing is basically equivalent to Synchronize. From top to bottom, only setTimeout is executed according to the order in which it is queued. That is to say, equivalent to ha, print it out first because the priority of then is higher than that of setTimeout

.

check microtask queue , there is a promise callback to be processed, go out of the queue and perform the p1 callback, and add promise to microtask queue during the callback. This is the first round of check. Continue to check microtask queue , find p2 callback, get out of the queue, and the second round ends.
check macrotask queue

Menu