I am not really sure I understand the difference between these two common scenarios.
Say we have this:
user.save().then(function(val){
anotherPromise1(val);
}).then(function(val){
anotherPromise2(val);
}).catch(function(err){
});
versus:
user.save().then(function(val){
return anotherPromise1(val);
}).then(function(val){
return anotherPromise2(val);
}).catch(function(err){
});
I know it makes a difference but how exactly?
If you don't return a value from the
then
callback, you're effectively returningundefined
. The nextthen
callback will run immediately, and seeundefined
as the resolution value.If you return a promise from the
then
callback, the secondthen
callback waits on that promise (indirectly, but that doesn't really matter), and when that promise is resolved, gets the resolution value from that promise.(This is covered by the
then
specification in the Promises/A+ spec, but slightly by omission — it doesn't explicitly mention what should happen ifonFulfilled
doesn't return anything, but in JavaScript, calling a function always gives you a resulting value; if the function doesn't explicitly return something,undefined
is the result of calling it. JavaScript doesn't have the concept ofvoid
methods a'la C/C#/C++/Java.)You can see it in this script live copy on Babel's REPL:
The output is (for example):
Note the differences between without a return and with a return:
Without,
anotherPromise2
was called immediately (as we can see from the elapsed time values) and receivedundefined
.With,
anotherPromise2
waited foranotherPromise
's resolution to occur, and then received84
(anotherPromise
's resolution value)The difference is the timing in this matter.
In example 1, the
save
promise is fullfilled and theanotherPromise1
will be invoked and because there is no promise returned, theanotherPromise2
will be invoked immediately.If you return the promise of the
anotherPromise1
function, the invokation ofanotherPromise
will happen, afteranotherPromise1
was resolved.So example 1:
anotherPromise1
andanotherPromise2
will be shot simultaneous While example 2:anotherPromise2
will wait foranotherPromise1
to be resolved