JS promise execution order

var p2 = new Promise(resolve => {
  setTimeout(() => {
    resolve()
  }, 2000)
})

var p1 = new Promise(resolve => {
  resolve(p2)
})

p1.then(data => {
  console.log("p1")
})

p2.then(data => {
  console.log("p2")
  console.log("p1 status ", p1) //  pending 
  Promise.resolve().then(() => {
    console.log("here") //  p1.then() 
  })
})

excuse me, when will the state of p1 change? Why is the state of p1 pending when console.log ("p1 status", p1) is executed? Thank you very much ~

Apr.29,2022

The resolve and reject parameters provided in

Promise are asynchronous, so they are later than synchronous code.

if the argument in the resolve function is a Promise instance, it will wait for the state of the instance to change. So the function in p1.then is executed at last, because the state of p1 cannot be changed until the state of p2 is determined, so p1 has not changed its state until console.log ('p1 status', p1) .

if it's hard to understand, I've written a Promise implementation before, so compare it with the above. learns and implements a Promise


The parameter p2 of

resolve is promise. The state of p1 will not change until the promise chain of p2 is fully executed.
that is, the then method of p1 must be executed after the last then method of p2.

The

then method is an asynchronous operation. If the Promise.resolve () parameter is empty, it returns directly.
therefore, the parameter of the then method of Promise.resolve () in p2's then method will first enter the asynchronous queue (earlier than the parameter of p1's then).

p1 waits for p2's then method to return undefined (a value is not shown here), and the state changes. Then the parameter of p1's then goes into the asynchronous queue.

Menu