Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use if expression in Promise.all()?

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

like image 376
Brick Yang Avatar asked Dec 25 '15 11:12

Brick Yang


2 Answers

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.

like image 57
Benjamin Gruenbaum Avatar answered Oct 01 '22 20:10

Benjamin Gruenbaum


Promise.all([ cond==true ? p1 : '', p2])
like image 36
Pra2win Avatar answered Oct 01 '22 21:10

Pra2win