Reputation: 15588
Trying to wrap my head around Javascript promises. I am experimenting with the Q library. I have some code that outputs what I expect, but I'm not sure how it is working:
'require strict';
var Q = require("q");
function getFirst(){
var deferred = Q.defer();
var first = 5;
console.log("getting first: " + first);
deferred.resolve(first);
return deferred.promise;
}
function addSecond(first){
var deferred = Q.defer();
var second = 10;
console.log("adding second: " + second);
var result = first + second;
deferred.resolve(result);
return deferred.promise;
}
function printResult(result) {
console.log("result is + " + result);
}
getFirst()
.then(addSecond)
.then(printResult);
Running this in Node i get:
getting first: 5
adding second: 10
result is + 15
What I'm confused about is how do addSecond and printResult get their parameters when they are eventually called? How did '5' magically make it into addSecond? What if addSecond needed a whole bunch of parameters?
Thanks for shedding light on this.
Upvotes: 1
Views: 72
Reputation: 1
Your addSecond code can be simplified to
function addSecond(first){
var second = 10;
console.log("adding second: " + second);
return first + second;
}
Upvotes: 0
Reputation: 754
When you call a promise it waits until underlying function "resolves", then call next function passing resolved value as parameter (this value is resolved on deferred.resolve(first)
). Then whether the new function returns a promise the cycle is repeated, otherwise just call next function passing returned value.
If you need to pass more than one parameter, you can return a array.
Great presentation of promises:
Upvotes: 0
Reputation: 86
Any parameter that you add to deferred.resolve([params]) is sent to the deferred function or DoneCallback (function indicated in .then(function)). It does accept multiple parameters (https://api.jquery.com/deferred.resolve/).
Upvotes: 1
Reputation: 113866
addSecond
gets its parameters from:
deferred.resolve(first);
so the value is 5
.
printResult
gets its parameters from:
var result = first + second;
deferred.resolve(result);
so the value is first + second
.
You can experiment with this. Pass the values you want to pass to your function into .resolve()
and see it changing. Basically, .resolve
is acting like a pointer to the function you pass to .then()
.
Upvotes: 1