Handling The Result Of Multiple Promises
In an Angular 1.X app, if I want to handle the result of two promises is there a more elegant way to achieve it than this: function doSomethingWithBothResults(result1, result2) {
Solution 1:
You could use Promise.all for this.
It would be something like this for your snippet:
let promises = [];
promises.push($http.get('/endpoint1'));
promises.push($http.get('/endpoint2'));
Promise.all ( promises ).then ( function ( data ) {
//Data from all the promises
} ).catch ( function ( error ) {
//Error
} );
In the callback function data
is an array whose each element contains the resolved value of the promise. Moreover, the order of the elements in data
is same as in which you pushed them in the array.
This would be useful, if your promises are independent of each other. If they require the result of a previous promise, chaining is the way to go. Also, this will start resolving both promises at the same time, while the chaining approach will wait for one to resolve and then start resolving the next one
Post a Comment for "Handling The Result Of Multiple Promises"