Javascript-完成所有嵌套的forEach循环后的回调

Rez*_*ami 3 javascript node.js async.js

我确定这是一个相当简单的任务,但是目前我无法将其包裹住。我有一组嵌套的forEach循环,并且需要在所有循环完成运行时进行回调。

我愿意使用async.js

这就是我正在使用的:

const scanFiles = function(accounts, cb) {
  let dirs = ['pending', 'done', 'failed'];
  let jobs = [];

  accounts.forEach(function(account) {
    dirs.forEach(function(dir) {
      fs.readdir(account + '/' + dir, function(err, files) {
         files.forEach(function(file) {
            //do something
            //add file to jobs array
            jobs.push(file);
         });
      });
    });
  });

  //return jobs array once all files have been added
  cb(jobs);
}
Run Code Online (Sandbox Code Playgroud)

Aro*_*ron 5

使用forEach的第二个参数index,您可以在每次运行最内部的循环时检查是否完成了所有循环。

因此,只需在代码中添加几行,您将获得以下信息:

const scanFiles = function(accounts, cb) {
    let dirs = ['pending', 'done', 'failed'];
    let jobs = [];

    accounts.forEach(function(account, accIndex) {
        dirs.forEach(function(dir, dirIndex) {
            fs.readdir(account + '/' + dir, function(err, files) {
                files.forEach(function(file, fileIndex) {
                    //do something
                    //add file to jobs array
                    jobs.push(file);

                    // Check whether each loop is on its last iteration
                    const filesDone = fileIndex >= files.length - 1;
                    const dirsDone = dirIndex >= dirs.length - 1;
                    const accsDone = accIndex >= accounts.length - 1;

                    // all three need to be true before we can run the callback
                    if (filesDone && dirsDone && accsDone) {
                        cb(jobs);
                    }
                });
            });
        });
    });
}
Run Code Online (Sandbox Code Playgroud)