Pregunta

I'm trying to run two different functions using promises (with Q.js) at the same time, and wait for response of both to run a third action.

I would like something like this:

run( promise1, promise2).done( callbackForBoth );

How can I do?

¿Fue útil?

Solución

You can use Q.all function, like this

Q.all([promise1, promise2]).then(callbackForBoth);

Normally, Q.all will be followed by .spread convenience method, which spreads the result from the Q.all call, as function parameters, like this

Q.all([promise1, promise2]).spread(function(pro1result, pro2result) {
    return callbackForBoth();
});

But the problem with this method is, if any of the promises are rejected, then rest of the promises will not be invoked.

So, if you want to make sure that all the promises are either fulfilled/rejected, you can use Q.allSettled in that case

Q.allSettled([promise1, promise2]).then(callbackForBoth);

Here also we can use the spread convenience method, but with a little more granularity. For each promise, we get an object, which has a state attribute to let the subsequent consumers to know if the promise was fulfilled or rejected. So, you might want to use the spread like this

Q.allSettled([promise1, promise2]).spread(function(pro1result, pro2result) {
    if (pro1result.state === "fulfilled" && pro2result.state === "fulfilled") {
        return callbackForBoth();
    } else {
        throw new Error("Not all of them were successful");
    }
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top