我想用来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
如果将promise用作值的代理,则可以使用s,也可以将promise嵌套一个级别(个人而言),我更喜欢将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.
});
将条件包装在a中new Promise
是显式构造,应避免使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句