Monday, 24 April 2017

making api calls in sync in nodejs

My code is something like this:

for(let query of array1){ 
   request.get(query, function(err, res, body){
     var array2 = body
     for (let query2 of array2){
        request.get(query, function(err, res, body){
            var variable1 = body
            updateDB(query, query2 , variable1)
         });
     }
   });
}

suppose Array1 is [1,2,3,4]

with first loop array2 will [a,b,c,d](and second loop will give [e,f,g,h] and so on).

Now my updateDB just updates for first value of array2[in above case just for a and e] in each loop. where as i want it to loop through all the elements of array2(like b, c, d) before it moves to second set of array2(i.e [e,f,g,h]).

I know this is happening because of async nature of js. But how can i fix it? How can I make outer loop to wait for inner loop to finish?

Hope so I am clear enough. Thanks In advance!!



via ankmachine

No comments:

Post a Comment