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 .
})
NS2 downloads,Angular js ,NS2 TCL Scripts,NS2 Install,NS2 Awk,Xgraph,NS2 research,NS2 problems,NS2 trace files, NS2 help,NS2 solutions,NS2 routing protocols download,MAODV download,PUMA download,AODV awk scripts,AODV throughput download,awk script for AODV,energy for AODV,end-toend delay for NS2,jitter for NS2,
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment