【问题标题】:How to use if expression in Promise.all()?如何在 Promise.all() 中使用 if 表达式?
【发布时间】:2016-03-31 11:09:01
【问题描述】:

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

看起来像这样:

functionA(); 

if(true) {
    functionB(); 
}

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

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

【问题讨论】:

    标签: javascript promise ecmascript-6


    【解决方案1】:

    好吧,如果您使用 Promise 作为值的代理,您可以使用 ifs,或者您可以将 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 中是explicit construction,应该避免。

    【讨论】:

    • 由于Promise.all() 将同化 以及承诺,第一个解决方案中的Promise.resolve() 可能是一个值,这将是一种注入默认值的廉价方式未调用 functionB() 时的值。 Demo.
    • 我同意调用 Promise.resolve() 是没用的。直接传递默认值,例如空或未定义。通过 doc 传递值而不是承诺是有效的:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    【解决方案2】:
    Promise.all([ cond==true ? p1 : '', p2])
    

    【讨论】:

    【解决方案3】:

    在我的情况下,我有多个条件

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多