繁体   English   中英

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

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

我想使用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()吗?

好吧,如果您使用 promise 作为值的代理,则可以使用if ,或者您可以将 promise 嵌套一层 - 就个人而言 - 我更喜欢使用它们作为它们的代理。 请允许我解释一下:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM