Benjamin RD
Benjamin RD

Reputation: 12034

Javascript/Node check if a loop with callback finish

Exist some way to know if a async loop in node.js (js) finish the last process to execute a new function or send a callback?

Upvotes: 1

Views: 1566

Answers (2)

Vinz243
Vinz243

Reputation: 9938

You need to use recursion:

do = function(i, data, callback){
    // if the end is reached, call the callback
    if(data.length === i+1)
       return callback()
    obj = data[i]
    doAsync(function(){
        // DO SOMETHING
        i++;
        // call do with the next object
        do(i, data, callback)
    });

}
do(0, [a, b, c], function(){
  THEN DO SOMETHING
});

So the same callback will be passed on do and when the end is reached, the callback will be executed. This method is quite clean yet if, for example, you need to crawl 50 pages each page will be loaded in a queue, waiting the other to finish before.

Using this function

| google.com | yahoo.fr      | SO.com    | github.com | calling callback!
|  (856ms)   | (936ms)       | (787ms)   |  (658ms)   |

Without

| google.com (1056ms)    | 
| yahoo.fr (1136ms)       |
| SO.com (987ms)        |
| github.com (856ms)   |

So another way would to count how many time the async function should be called and each time one is ended, you increment a var, and when said var reached the length, you call the callback.

do = function(data, callback){
    var done = 0;
    data.forEach(function(i, value){
       doAsync(function(){
           done++;
           if(done === data.length)
               callback()
       });
    });

}
do(0, [a, b, c], function(){
  THEN DO SOMETHING
});

Then it will be

| google.com (1056ms)    | 
| yahoo.fr (1136ms)       | calling callback!
| SO.com (987ms)        |
| github.com (856ms)   |
done = 0               1234

Upvotes: 2

Denis Ivanov
Denis Ivanov

Reputation: 905

Take a look at this library. It seems that 'each' iterator would suit your needs.

Upvotes: 1

Related Questions