Nitya
Nitya

Reputation: 163

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
       })
   }
}

Upvotes: 7

Views: 24391

Answers (5)

Amit
Amit

Reputation: 2255

You can do it in multiple ways. We can also use for of loop with async..await to get the result synchronously while looping, if that is a requirement. Something like this:

function downloadPage(url) {    
    return Promise.resolve('some value'); 
}

async function () {    
    for(let url of urls) {
       let result = await downloadPage(url);
       // Process the result 
       console.log(result);    
    } 
}

Upvotes: 0

Promil Bhardwaj
Promil Bhardwaj

Reputation: 76

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

Upvotes: 2

Redu
Redu

Reputation: 26161

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));

Upvotes: 6

Carol Skelly
Carol Skelly

Reputation: 362320

You could do something like this..

var arr=[],arr2=[];
for (var i = 0, i<jsonData.length; i++){
   if(someCOndition){
       //push onto the array inputs for getSomeData()
       arr.push(jsonData[i]);
   }
  if(someOtherCOndition){
       arr2.push(jsonData[i]);
   }
}

processArr(0);
processArr2(0);

function processArr(idx){
    if (idx>=arr.length) {
        //done
    }
    else {
        getSomeData().then(function(data){
          // some operation using data
          // optionally store in a results array

          // recurse
          processArr(idx+1)

       })
    }
}

function processArr2(idx){
    if (idx>=arr2.length) {
        //done
    }
    else {
        getSomeotherData().then(function(data){
          // some operation using data

          // recurse
          processArr2(idx+1)
       })
    }
}

Upvotes: -1

mdziekon
mdziekon

Reputation: 3627

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).

Upvotes: 12

Related Questions