Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous calls inside loop [duplicate]

Possible Duplicate:
Coordinating parallel execution in node.js

First, hands on pseudo-code:

forEach(arrayelements) {
  asyncQueryFunction(function(qres) {
    //work with query results.
  });
}
// finally, AFTER all callbacks did return:
res.render("myview");

How to do that?

If that wasn't clear enough, I would explain:

I need to do a series of "update" queries (in mongodb, via mongoose), looping over a list of document ids. For each id in my array I will call an asynchronous function which will return query results (I don't need to do anything with them, actually).

I know I have to use .forEach() javascript loop, but how can I execute my "final" callback only when ALL of my asynchronous queries did finish?

I'm already using the excellent async library (https://github.com/caolan/async) for achieving this kind of task when I've got a "limited" series of task to execute. But I don't think I can pass it an array of different functions.

CAN I?

like image 487
Fabio B. Avatar asked Sep 18 '12 07:09

Fabio B.


1 Answers

very simple pattern is to use 'running tasks' counter:

var numRunningQueries = 0
forEach(arrayelements) {
  ++numRunningQueries;
  asyncQueryFunction(function(qres) {
    //work with query results.
    --numRunningQueries;
    if (numRunningQueries === 0) {
       // finally, AFTER all callbacks did return:
       res.render("myview");
    }
  });
}

or, alternatively, use async helper library such as Async.js

like image 80
Andrey Sidorov Avatar answered Nov 09 '22 20:11

Andrey Sidorov