简体   繁体   English

Javascript / Node检查回调完成的循环

[英]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. 因此,相同的回调将在do上传递,当到达结束时,将执行回调。 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. 这个方法非常干净但是,例如,如果你需要抓取50个页面,每个页面将被加载到队列中,等待另一个页面完成之前。

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. 因此,另一种方法是计算应该调用异步函数的次数,每次结束时,增加一个var,当所述var达到该长度时,调用回调。

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. 似乎“每个”迭代器都适合您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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