Pregunta

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:

http://jsfiddle.net/D6m8V/

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:

http://jsfiddle.net/3x6v3/2/

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?

¿Fue útil?

Solución

One option would be to use Q.all (Promise.all in ES6 promises and other libraries like Bluebird)

getOriginalString().then(function(orig){
    return Q.all([orig,uppercase(x)]);
}).spread(function(orig,upper){
    console.log(orig,upper);
});

You can of course still use a closure like the callback version (with nesting, or an outer scope).

Also, just to make sure, you don't need to promisify any function that doesn't make an I/O or otherwise asynchronous call.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top