8

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()?

Brick Yang
  • 5,388
  • 8
  • 34
  • 45

3 Answers3

12

Well, you can use ifs 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.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • As `Promise.all()` will assimilate *values* as well as promises, that `Promise.resolve()` in the first solution could be a value, which would be an inexpensive way to inject a default value when `functionB()` is not called. [Demo](https://jsfiddle.net/fabup5aq/). – Roamer-1888 Dec 25 '15 at 20:32
  • I agree that calling Promise.resolve() is useless. Pass directly default value e.g. null or undefined. By doc it is valid to pass values instead of promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all – mikep Jul 30 '20 at 12:58
4
Promise.all([ cond==true ? p1 : '', p2])
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Pra2win
  • 63
  • 8
3

In my case i had multiple conditions

 functionA(); 
 if(condition1) {
  functionX(); 
 }else if (condition2) {
  functionY(); 
 }....

so i did the following

const promises = [];
promises.push(functionA());
if (condition1) promises.push(functionX());
else if (condition2) promises.push(functionY());
......

Promise.all(promises).then((results) => console.log('results', results) );
thr
  • 163
  • 12