Problem: Promises resolve only with a single value. If you want to pass on the result of PromiseCall1 to PromiseCall2, you have different options:
You can nest a .then()
for Promise Call 2 and return both value from the scope.
- Nesting makes it harder to read and should be avoided
delay("A")
.then(function (A) {
return delay("B")
//nested then with access to A and B
.then(function (B) {
return [A, B];
});
})
.then(function (result) {
console.log(result[0]); //= A
console.log(result[1]); //= B
});
You could use Promise.all
to resolve the value A and the Promise call for B.
- No more nesting
Promise.all()
is harder to grasp thenreturn [A, B]
delay("A")
.then(function (A) {
return Promise.all([A, delay("B")]);
})
.then(function (result) {
console.log(result[0]); //= A
console.log(result[1]); //= B
});
You could store the state within the function, so every nested then can access it.
- keeping state in a scope object makes the function harder to grasp
- might be a valid soltion for long promise chains
function ABC() {
var state = {};
delay("A")
.then(function (A) {
//store A in state for the next .then()
state.A = A;
return delay("B");
})
.then(function (B) {
console.log(state.A); //= A
console.log(B); //= B
});
}