Why is promise resolving with undefined?

2019-02-25 10:24发布

问题:

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

The console log output is

'hello'
undefined

I know this is not the best way to write this promise chain, but I was wondering why the last .then executes at all. I'm not returning anything with console.log('hello'), so wouldn't the .then off of the second promise never resolve?

回答1:

Because you've chained several promises together and one of your .then() handlers returns nothing.

This part:

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

value });

returns nothing which is essentially the same as return undefined and therefore the resolved value of the chain becomes undefined.

You can change it to this to preserve the resolved value:

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

Remember that the return value of every .then() handler becomes the resolved value of the chain going forward. No return value makes the resolved value be undefined.



回答2:

Your last .then is receiving the result created in your nested Promise, and, since you are not returning anything ( i.e. you are just doing console.log('hello') ) then result is undefined. You can see this behaviour if you actually return something :

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

    firstPromise
      .then(() => {
        return new Promise((resolve, reject) => {
          resolve("second promise");
        }).then(result => {
          console.log("hello");
          return "something";
        });
      })
      .then(result => {
        console.log(result);
      });
  }   

this would output :

'hello'
'something'


标签: promise