这种行为的解释是什么:ES6 Promise that is never resolved

What's the explanation for this behavior: ES6 Promise that is never resolved

以下代码:

Promise.resolve('a string')
  .then(resp => {
    console.log('resp from the initial promise: ' + resp)
    const p0 = new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('finished sleeping in p0')
        resolve('hello from p0')
      }, 5000)
    })
    console.log('returning p0')
    return p0
  })
  .then(resp => {
    console.log('resp from p0: ' + resp)
    const p1 = new Promise((resolve, reject) => {
      console.log('p1 completed')
      // resolve('another string from p1')
    })
    console.log('returning p1')
    return p1
  })
  .then(res => {
    console.log('resp from p1: ' + res)
  })
  .catch(err => {
    console.error('Error: ' + err.message)
  })

console.log('last statement')

当我 运行 时,我得到以下输出(这对我来说没有意义)

last statement
resp from the initial promise: a string
returning p0
finished sleeping in p0
resp from p0: hello from p0
p1 completed
returning p1

首先,由于 promise p1 从未得到解决,我希望程序永远等待并且永远不会完成。事实并非如此,它完成得很好(尽管没有到达最后一个then())。

此外,它创建承诺并在创建承诺之后的代码之前执行承诺内的代码。我希望 'returning p1' 在 之前 'p1 completed' 因为我假设承诺中的内容将在下一个滴答时执行。

Also, it creates the promise and executes the code inside of the promise before the code that comes after it's created. I would expect 'returning p1' to come before 'p1 completed' since I assumed that what's inside the promise would be executed on the next tick.

如果您在一个承诺上调用 .then,您传入的函数将延迟到下一个 tick。但是 promise 的构造函数不会那样做。当你构造一个 new Promise 时,你传递给构造函数的代码是立即同步的 运行。所以这段代码:

const p0 = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('finished sleeping in p0')
    resolve('hello from p0')
  }, 5000)
})
console.log('returning p0')

... 将立即设置超时,甚至在 promise 被分配给 p0 之前。而这段代码:

const p1 = new Promise((resolve, reject) => {
  console.log('p1 completed')
  // resolve('another string from p1')
})
console.log('returning p1')

... 将立即注销 'p1 completed',甚至在 promise 被分配给 p1.

之前