I'm trying to use async
to iterate over a directory of images within an async waterfall
array of functions.
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. 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?
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.
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.