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

Bri*_*ang 6 javascript promise ecmascript-6

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

它看起来像这样:

functionA(); 

if(true) {
    functionB(); 
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Ben*_*aum 9

好吧,if如果您使用 promise 作为值的代理,则可以使用s,或者您可以将 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
});
Run Code Online (Sandbox Code Playgroud)

或者类似的:

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

将条件包装在 a 中new Promise显式构造,应该避免。