简体   繁体   English

async.each/forEachOf 进入下一次迭代而不调用回调

[英]async.each/forEachOf entering next iteration without calling callback

I'm trying to use async to iterate over a directory of images within an async waterfall array of functions.我正在尝试使用async来迭代异步waterfall函数数组中的图像目录。

async.waterfall([
function(callback){
  async.forEachOf(waterfallObj.sizeDirs, function(sizeDir, index, cb){
      //get image files
      fs.readdir(path.join(__dirname, sizeDir), function(err, files){
        tempFiles = files;
        console.log(index); //0 1 2 3 4
        //cb();
      });
  });

  callback(null);
}, /*more functions*/
]);

The idea is that I don't want to do the next iteration in the forEachOf loop until the readdir finishes reading files.这个想法是我不想在forEachOf循环中进行下一次迭代,直到readdir完成读取文件。 To my understanding, forEachOf will not enter the next cycle of its loop until its callback is called (just like each function in async waterfall or series . However even with cb() commented out like I have above, I still see the index printed 5 times. Why does it not stop with the first iteration? How can I ensure the the readdir will finish before the next iteration if cb does not do this? What is cb supposed to do exactly if not this? (I've also had this same effect using async.each . Should I be using native forEach perhaps?据我所知, forEachOf不会进入循环的下一个循环,直到它的回调被调用(就像异步waterfallseries每个函数一样。但是即使cb()像我上面那样注释掉,我仍然看到索引打印 5次。为什么它不会在第一次迭代时停止?如果cb不这样做,我如何确保 readdir 将在下一次迭代之前完成?如果不是这个, cb应该做什么?(我也有这个使用async.each效果相同。我应该使用原生forEach吗?

That's the whole point of an asynchronous process, you don't wait for a request to finish before firing the next one.这就是异步过程的全部意义所在,在触发下一个请求之前,您无需等待请求完成。 You fire all requests and they will get resolved one by one and each one of them will call it's callback as soon as the thread is free (and, of course, the request has finished).您触发所有请求,它们将一一得到解决,一旦线程空闲(当然,请求已完成),每个请求都会调用它的回调。

Maybe you are looking for the promise approach, where you can chain your promises so that when one promise gets resolved, the next request will be fired and create a new promise, which, redundantly, you will be able to chain your third request, and so on.也许您正在寻找承诺方法,您可以在其中链接您的承诺,以便当一个承诺得到解决时,下一个请求将被触发并创建一个新的承诺,多余地,您将能够链接您的第三个请求,并且很快。

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

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