如何在 Promise.all() 中使用 if 表达式

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

本文关键字:if 表达式 Promise all      更新时间:2023-09-26

我想用Promise.all()来处理两个 promise 对象,但第二个是内部的 if 表达式。如何处理这种情况?

它看起来像这样:

functionA(); 
if(true) {
    functionB(); 
}

functionA()functionB() 都返回一个 promise 对象。在正常情况下,我可以使用

Promise.all([
    functionA(),
    functionB()
]).then(resule => {
    console.log(result[0]);  // result of functionA
    console.log(result[1]);  // result of functionB
})

但是如何处理if表达式呢?我应该把if(true){functionB()}包在new Promise()里吗?

好吧

,如果您使用承诺作为值的代理,您可以使用 if s,或者您可以将承诺嵌套一个级别 - 个人 - 我更喜欢使用它们作为代理。请允许我解释一下:

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
});

或类似:

var p1 = functionA();
var p2 = condition ? Promise.all([p1, functionB()]) : p1; 
p2.then(results => {
     // either array with both results or just p1's result.
});

将条件包装在new Promise中是显式构造,应避免使用。

Promise.all([ cond==true ? p1 : '', p2])

就我而言,我有多种条件

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

所以我做了以下工作

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) );