Why is promise resolving with undefined?

19,442

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

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.

Share:
19,442

Related videos on Youtube

user1411469
Author by

user1411469

Updated on September 15, 2022

Comments

  • user1411469
    user1411469 over 1 year

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

    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?

    • 4castle
      4castle almost 7 years
      Returning nothing just means returning undefined. Also, your code would be much simpler if you did Promise.resolve('first promise') instead of using the Promise constructor.
  • user1411469
    user1411469 almost 7 years
    I see. I didn't realize there was an implicit return. Didn't make the connection that all js functions have this behavior.
  • dkjain
    dkjain over 5 years
    This statement clears it up 'Remember that the return value of every .then() handler becomes ...'. Kudos