Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is promise resolving with undefined?

Tags:

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

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?

like image 203
user1411469 Avatar asked Jul 13 '17 23:07

user1411469


People also ask

How do you know if a promise is resolved or not?

The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

What happens if you dont resolve promise?

A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.

What happens when you resolve a promise?

resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happened: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state.


1 Answers

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.

like image 108
jfriend00 Avatar answered Nov 02 '22 04:11

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!