Tuesday 16 May 2017

How to call async functions in loops - javascript

Hey There i came across an issue recently while performing the Async db calls inside for loops in javascript.

ex:

for (let i=0 ; i<10 ; i++) {
   db.User.find({},function(err,res){
            console.log(i);
   });
}

Consider above code snippet. Here if you see db is a database call and it takes obviously time to execute query and hit call back but our for loop wont wait till it hit the call back. The for loop will be executed even before you receive the result from call back.

So you will not get actual result .

How I solved it

I used promises to solve it
q is a  package from NOde js and in angular js (Now Angular 2 moved to Observables)

Steps:

1. Frame all the async function calls you want to make in for loop.
2. Pass all this async calls in Q.all() function. (Q.all will get all the promise objects from the async functions you pass and club in the form of array.)
3. Now using this array you can map and reduce the results.


Ex:

asyncFunc1()
 {
setTimeout(function() {
return 'Hello' }, 3000); // consider this returns after 3 s of execution
}

asyncFunc2()
{
setTimeout(function() {
return 'Hello' }, 5000); // consider this returns after 5 s of execution
}

asyncFunc3()
{
setTimeout(function() {
return 'Hello' }, 2000); // consider this returns after 2 s of execution
}


var asyncCalls = [];
asyncCalls[0] = asyncFunc1();
asyncCalls[1] = asyncFunc2();
asyncCalls[2] = asyncFunc3();


now pass this array of function calls to Q.all like below


var Q = require('q');

Q.all(asynCalls,function(res) {

console.log(res)  // this result is nothing but array of collecting objects from asynccalls. now you can

//map and reduce the results according to you .


})






No comments:

Post a Comment