How to use if expression in Promise.all()?
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.