When will you check the status of Promise?

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() 
  })
})

because the state of p1 is determined by the state of p2, and then, ah, when I call Promise.resolve (). Then () in p2.then () , the output will take precedence over p1.then () . Why? I guess the state of p1 will not be changed until the next event loop?

can you give me some advice? thank you very much.

Sep.12,2021

is detected in the same loop, but in sequence.

...

p1.then(data => {
  console.log('p1')//p1 fulfilled callback
})

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

add

before Promise.resolve ()
setTimeout(()=>{
  console.log('setTimeout')
}, 0)

print result is

here
p1
setTimeout

indicates that it is the same event loop. My understanding is that Promise.resolve () actually has fulfilled , p1 fulfilled after it, the callback order should also be p1 followed by

.
Menu