为什么用undefined解决promise?

use*_*469 5 promise

var firstPromise = new Promise((resolve, reject) => {
  resolve('first promise');
});

firstPromise.then(() => {
  return new Promise((resolve, reject) => {
    resolve('second promise');
  }).then((result) => {
    console.log('hello');
  });
}).then((result) => {
  console.log(result);
});
Run Code Online (Sandbox Code Playgroud)

控制台日志输出为

'hello'
undefined
Run Code Online (Sandbox Code Playgroud)

我知道这不是编写此Promise链的最佳方法,但我想知道为什么最后一个方法会.then执行。我什么都不会退回console.log('hello'),所以第二个承诺中的.then永远不会解决吗?

jfr*_*d00 5

因为您已将多个promise链接在一起,而您的一个.then()处理程序却一无所获。

这部分:

.then((result) => {
  console.log('hello');
  // since there is no return value here, the promise chain's resolved
  // value becomes undefined
Run Code Online (Sandbox Code Playgroud)

值});

不会返回与基本上相同的任何东西,return undefined因此链的解析值变为undefined

您可以将其更改为保留解析的值:

.then((result) => {
  console.log('hello');
  return result;         // preserve resolved value of the promise chain
});
Run Code Online (Sandbox Code Playgroud)

请记住,每个.then()处理程序的返回值都将成为链的解析值。没有返回值会使解析值变为undefined