I have two asynchronous functions that need to be executed sequentially (the second one depends on the first one's result), and once they've executed, I need to use the results of both functions. In a "classical" callback based pattern, that's pretty easy:
function getOriginalString(callback) {
callback("An original string");
}
function uppercase(x, callback) {
callback(x.toUpperCase());
}
getOriginalString(function(orig) {
uppercase(orig, function(upper) {
console.log(orig, upper); //Access to both results
});
});
I'm trying to redo this using Q promises. Here's what I got:
function getOriginalString() {
var deferred = Q.defer();
deferred.resolve("An original string");
return deferred.promise;
}
function uppercase(x) {
var deferred = Q.defer();
deferred.resolve(x.toUpperCase());
return deferred.promise;
}
getOriginalString()
.then(uppercase)
.then(function(result) {
console.log(result);
})
.done();
The problem is that I only have access to the result from the last function call, uppercase
. I need to have access to the result from both functions, like in the callback based example.
What's the proper way of doing this with promises?