简体   繁体   中英

Javascript/Node check if a loop with callback finish

是否存在某种方式来了解node.js(js)中的异步循环是否完成了执行新函数或发送回调的最后一个进程?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM