Given
function doStuff(n /* `n` is expected to be a positive number */) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(n * 10)
}, Math.floor(Math.random() * 1000))
})
.then(function(result) {
if (result > 100) {
console.log(result + " is greater than 100")
} else {
console.log(result + " is not greater than 100");
}
})
}
doStuff(9)
.then(function(data) {
console.log(data) // `undefined`, why?
})
Why is data
undefined
at .then()
chained to doStuff()
call?
The problem were facing:
As you may already noticed, then returns a new promise. This has a good reason, it makes promise chaining easy, e.g:
But this also creates the small trap, we are facing. The solution could be returning the original promise and not the new promise automatically returned by .then() as this is resolved to undefined as the function inside then is not explicitly returning something:
So as you can see, to return the original promise, we simply store it in a variable, then assign a .then handler to it, and have still a reference to the original promise which we can assign other handlers to ( or return ).
In action:
You are not returning the result from the .then() chained to the Promise. You need to add return result; to the .then()
Because no
Promise
or other value isreturn
ed from.then()
chained toPromise
constructor.Note that
.then()
returns a newPromise
object.The solution is to
return
a value or other function call whichreturn
s a value orPromise
from.then()
.The doStuff is returning the
Promise
. But, your lastthen
function is not returning any values, hencedata
is coming asundefined
.In promises, value of arguments of the next
then
function is the returned value of the previousthen
function.Because your data value is the return value of the last
.then()
, your last.then()
doesn't have a valid return value.So, you can add the return value in the last
.then()
function.