Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving promises inside for loop

I am trying to read a JSON object using a for loop to format the JSON data and send it back to the client by putting the formatted response into a model object.

Inside for loop, i am dealing with two promises based upon few conditions. There are two functions, each having a promise returned.How can I get my final data after all the promises are resolved? Thanks in advance.

for (var i = 0, i<jsonData.length; i++){
   if(someCOndition){
       getSomeData().then(function(data){
          //some operation using data
       })
   }
  if(someOtherCOndition){
       getSomeOtherData().then(function(data){
          //some operation using data
       })
   }
}
like image 747
Nitya Avatar asked Sep 03 '16 16:09

Nitya


3 Answers

Promise.all([ promise1, promise2 ]) (Promise.all() on MDN) in case of standard JS Promises (ES2015+). It returns a new promise, which gets resolved once all passed promises get resolved. But be aware - it will get rejected immediately when at least one promise gets rejected (it won't wait for any other promise).

like image 54
mdziekon Avatar answered Sep 20 '22 23:09

mdziekon


You might do as follows;

var promises = [],
  JSONData_1 = ["chunk_11","chunk_12","chunk_13"],
  JSONData_2 = ["chunk_21","chunk_22","chunk_23"],
 getJSONData = (b,i) => new Promise((resolve,reject) => setTimeout(_ => b ? resolve(JSONData_1[i])
                                                                          : resolve(JSONData_2[i]),1000));

for (var i = 0; i < JSONData_1.length; i++){
   if(Math.random() < 0.5) promises.push(getJSONData(true,i));
   else promises.push(getJSONData(false,i));
}
Promise.all(promises)
       .then(a => console.log(a));
like image 43
Redu Avatar answered Sep 17 '22 23:09

Redu


You can use jQuery.when().

  var deferredList = [];
    for (var i = 0, i<jsonData.length; i++){
       if(someCOndition){

         deferredList.push(getSomeData().then(function(data){
         //some operation using data
         }))
        }
   if(someOtherCOndition){

       taskList.push(getSomeOtherData().then(function(data){
        //some operation using data
       }))
    }
   }
 JQuery.when(taskList).done(function(){
      // final to do..
 }).fail(){
    // even if single one fails ! be aware of this
   }

jQuery.when() MDN

like image 25
Promil Bhardwaj Avatar answered Sep 19 '22 23:09

Promil Bhardwaj