I have a for loop which does many iterations .I would like to put that piece of code in a custom async function as it is blocking.Is there anyway I can write a function so it will call a callback once the loop iteration is over?.
-
1If you don't have any non-blocking operations, async will not help you at all. Read blog.slaks.net/2014-12-23/parallelism-async-threading-explainedSLaks– SLaks2015-02-16 16:19:02 +00:00Commented Feb 16, 2015 at 16:19
-
i would change my look for a recursive function and and always defer the next execution to the next tickDayan Moreno Leon– Dayan Moreno Leon2015-02-16 16:31:54 +00:00Commented Feb 16, 2015 at 16:31
-
you may have a look at async library -github.com/caolan/asyncPiyas De– Piyas De2015-02-16 16:49:48 +00:00Commented Feb 16, 2015 at 16:49
-
As SLaks stated this approach is not really useful. If you have a very work intensive Loop there, you could maybe think about extracting it into another NodeJS-Process and call it with the child-process lib.David Losert– David Losert2015-02-16 16:49:50 +00:00Commented Feb 16, 2015 at 16:49
-
That sounds good, but how do I fork another process?..isnt node single threaded?Pranav kirtani– Pranav kirtani2015-02-16 17:27:02 +00:00Commented Feb 16, 2015 at 17:27
|
Show 1 more comment
1 Answer
Use asynchronous-function-inside-a-loop paradigm. This ensures that the asynchronous functions get called with the correct value of the index variable.
var total = someObject.list.length;
var count = 0;
for(var i = 0; i < total; i++){
(function(foo){
myobj.get(someObject.list[foo], function(err, response) {
do_something(foo);
count++;
if (count > total - 1) done();
});
}(i)); //To immediately invoke the function passing 'i' as parameter
}
function done() {
console.log('All data loaded');
}