Ich möchte Promise.all()
verwenden, um zwei Versprechungsobjekte zu behandeln, aber das zweite ist ein innerer if
Ausdruck. Wie gehe ich mit dieser Situation um?
Es sieht aus wie das:
functionA();
if(true) {
functionB();
}
functionA()
und functionB()
geben beide ein Versprechen-Objekt zurück. Im Normalfall könnte ich verwenden
Promise.all([
functionA(),
functionB()
]).then(resule => {
console.log(result[0]); // result of functionA
console.log(result[1]); // result of functionB
})
Aber wie geht man mit dem Ausdruck if
um? Soll ich das if(true){functionB()}
in ein new Promise()
einwickeln?
3 Antworten
Nun, Sie können if
verwenden, wenn Sie Versprechen als Stellvertreter für Werte verwenden, oder Sie können das Versprechen auf einer Ebene verschachteln - persönlich - ich bevorzuge es, sie als Stellvertreter zu verwenden. Lassen Sie mich erklären:
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
});
Oder ähnlich:
var p1 = functionA();
var p2 = condition ? Promise.all([p1, functionB()]) : p1;
p2.then(results => {
// either array with both results or just p1's result.
});
Das Umschließen der Bedingung in ein new Promise
ist explizite Konstruktion und sollte vermieden werden.
Promise.all([ cond==true ? p1 : '', p2])
In meinem Fall hatte ich mehrere Bedingungen
functionA();
if(condition1) {
functionX();
}else if (condition2) {
functionY();
}....
Also habe ich folgendes gemacht
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) );