javascript - handling the result of multiple promises -


in angular 1.x app, if want handle result of 2 promises there more elegant way achieve this:

function dosomethingwithbothresults(result1, result2) {   return result 1 + result2; }  $http.get('/endpoint1').then(function (result1) {    $http.get('/endpoint2').then(function (result2) {     dosomethingwithbothresults(result1 + result2);   }); }); 

while fine when there 2 promises, deep nesting result larger number unsettling.

you use promise.all this.

it snippet:

let promises = []; promises.push($http.get('/endpoint1')); promises.push($http.get('/endpoint2'));  promise.all ( promises ).then ( function ( data ) {     //data promises } ).catch ( function ( error ) {    //error } ); 

in callback function data array each element contains resolved value of promise. moreover, order of elements in data same in pushed them in array.

this useful, if promises independent of each other. if require result of previous promise, chaining way go. also, start resolving both promises @ same time, while chaining approach wait 1 resolve , start resolving next one


Comments

Popular posts from this blog

javascript - Training Neural Network to play flappy bird with genetic algorithm - Why can't it learn? -

service - Android MediaPlayer calls onCompletion before it already finished -

javascript - Create a stacked percentage column -