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
.
Related videos on Youtube
Author by
user1411469
Updated on September 15, 2022Comments
-
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 withconsole.log('hello')
, so wouldn't the .then off of the second promise never resolve?-
4castle almost 7 yearsReturning nothing just means returning
undefined
. Also, your code would be much simpler if you didPromise.resolve('first promise')
instead of using thePromise
constructor.
-
-
user1411469 almost 7 yearsI see. I didn't realize there was an implicit return. Didn't make the connection that all js functions have this behavior.
-
dkjain over 5 yearsThis statement clears it up 'Remember that the return value of every .then() handler becomes ...'. Kudos