I want to use Promise.all()
to handle two promise object, but the second is inner a if
expression. How to handle this situation?
It looks like this:
functionA();
if(true) {
functionB();
}
functionA()
and functionB()
both return a promise object. In normal case, I could use
Promise.all([
functionA(),
functionB()
]).then(resule => {
console.log(result[0]); // result of functionA
console.log(result[1]); // result of functionB
})
But how to handle with the if
expression? Should I wrap the if(true){functionB()}
in a new Promise()
?
Well, you can use if
s if you use promises as proxies for values, or you can nest the promise one level - personally - I prefer using them as the proxies they are. Allow me to explain:
var p1 = functionA();
var p2 = condition ? functionB() : Promise.resolve(); // or empty promise
Promise.all([p1, p2]).then(results => {
// access results here, p2 is undefined if the condition did not hold
});
Or similarly:
var p1 = functionA();
var p2 = condition ? Promise.all([p1, functionB()]) : p1;
p2.then(results => {
// either array with both results or just p1's result.
});
Wrapping the conditional in a new Promise
is explicit construction and should be avoided.
Promise.all([ cond==true ? p1 : '', p2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With