Javascript - Callback after all nested forEach loops are done


Reza Karami

I'm sure this is a fairly simple task, but at the moment I can't figure it out. I have a set of nested forEach loops and need a callback when all loops have finished running.

I am willing to use async.js

This is what I'm using:

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);
}
Aaron

Using forEachthe second argument index, you can check if all loops are completed each time you run the innermost loop.

So just add a few lines to your code and you will get:

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);
                    }
                });
            });
        });
    });
}

Related


Javascript - Callback after all nested forEach loops are done

Reza Karami I'm sure this is a fairly simple task, but at the moment I can't figure it out. I have a set of nested forEach loops and need a callback when all loops have finished running. I am willing to use async.js This is what I'm using: const scanFiles = fu

Javascript - Callback after all nested forEach loops are done

Reza Karami I'm sure this is a fairly simple task, but at the moment I can't figure it out. I have a set of nested forEach loops and need a callback when all loops have finished running. I am willing to use async.js This is what I'm using: const scanFiles = fu

Javascript - Callback after all nested forEach loops are done

Reza Karami I'm sure this is a fairly simple task, but at the moment I can't figure it out. I have a set of nested forEach loops and need a callback when all loops have finished running. I am willing to use async.js This is what I'm using: const scanFiles = fu

Javascript - Callback after all nested forEach loops are done

Reza Karami I'm sure this is a fairly simple task, but at the moment I can't figure it out. I have a set of nested forEach loops and need a callback when all loops have finished running. I am willing to use async.js This is what I'm using: const scanFiles = fu

Javascript: Improve code with nested foreach loops

Saran 3h Just wondering if the two forEach loops can be flattened or can be replaced with any other more efficient solution. My GOOGLE_CRITERIA list is too long (~1000 elements) and the nested forEach loops are too much. const openAddressSearch = ({ addressRes

Callback after all async forEach callbacks complete

Andreasson: as the title suggests. What should I do? I want to call whenAllDone()after the forEach loop goes through each element and does some async processing . [1, 2, 3].forEach( function(item, index, array, done) { asyncFunction(item, function itemD

Callback after all async forEach callbacks complete

Andreasson: as the title suggests. What should I do? I want to call whenAllDone()after the forEach loop goes through each element and does some async processing . [1, 2, 3].forEach( function(item, index, array, done) { asyncFunction(item, function itemD

Callback after all async forEach callbacks complete

Andreasson: as the title suggests. What should I do? I want to call whenAllDone()after the forEach loop goes through each element and does some async processing . [1, 2, 3].forEach( function(item, index, array, done) { asyncFunction(item, function itemD

Remove nested foreach loops

node_man In my code, I use two forEach loops. But in order to optimize my code, I have been instructed not to use a forEach loop inside a forEach loop. So I don't want to iterate over the second array obj3. I just want to save the value somewhere without using

Nested foreach loops in Powershell

unknown I am trying to read values from the file abc.txt in the following function abc.txt a=abcdef123 b=ngh567 c=defh123 Here is the function: function List { Write-Output "Below are the window boxes" $alph = @(get-content -Path "abc.tx

Nested foreach loops in Powershell

unknown I am trying to read values from the file abc.txt in the following function abc.txt a=abcdef123 b=ngh567 c=defh123 Here is the function: function List { Write-Output "Below are the window boxes" $alph = @(get-content -Path "abc.tx

Nested foreach loops with pointers?

Dmitry Sokolov map<string, vector<int>*> settings for (auto el : settings) { for(auto i : el) { cout << i; } } I got inner el: This range-based "for" statement requires a suitable start function, but didn't find one

Remove nested foreach loops

node_man In my code, I use two forEach loops. But in order to optimize my code, I have been instructed not to use a forEach loop inside a forEach loop. So I don't want to iterate over the second array obj3. I just want to save the value somewhere without using

Nested foreach loops in Powershell

unknown I am trying to read values from the file abc.txt in the following function abc.txt a=abcdef123 b=ngh567 c=defh123 Here is the function: function List { Write-Output "Below are the window boxes" $alph = @(get-content -Path "abc.tx

Nested incrementing foreach loops

rebellion What is the idiomatic way to get something like this? ((fn [coll] (function-body)) [:a :b :c :d]) -> [[:a :b][:a :c][:a :d][:b :c][:b :d][:c :d]] I can only do it this way. #(for [i (range (count %)) j (range (inc i) (count %))] [(nth % i

Nested foreach loops in Powershell

unknown I am trying to read values from the file abc.txt in the following function abc.txt a=abcdef123 b=ngh567 c=defh123 Here is the function: function List { Write-Output "Below are the window boxes" $alph = @(get-content -Path "abc.tx

Nested foreach loops in Powershell

unknown I am trying to read values from the file abc.txt in the following function abc.txt a=abcdef123 b=ngh567 c=defh123 Here is the function: function List { Write-Output "Below are the window boxes" $alph = @(get-content -Path "abc.tx