Un1
Un1

Reputation: 4132

Cannot add up results of a function in a loop

I have this function getSize() (from npm module: get-folder-size) that's calculating the total size of all files in a folder (directory).

const getSize = require('get-folder-size')

let folders = ["C:\\test folder", "C:\\test folder 2\\sub folder"]

funciton totalFilesizeOfAllFolders () {
  let totalSizeOfAllFolders = 0
  this.folders.forEach(folder => {
    getSize(folder, (err, size) => {
      if (err) { throw err }
      // ADD UP THE "SIZE" TO THE TOTAL SOMEHOW
      // Just doing the following returns 0: totalSizeOfAllFolders += size
    })
  })
  return totalSizeOfAllFolders 
}

Question

How do I loop through the array folders properly and add up the calculated sizes of all the folders in the array? I'm not sure how to return the size out of the function

Upvotes: 0

Views: 82

Answers (2)

Cookie
Cookie

Reputation: 595

You could use a library like Async to help you iterate over the calls asynchronously then pass a callback to your function to return the totalSizeOfAllFolders.

function totalFilesizeOfAllFolders (done) {
  let totalSizeOfAllFolders = 0;
  async.each(folders, (folder, callback) => {
    getSize(folder, (err, size) => {
      if (err) { throw err }
      totalSizeOfAllFolders++;
      callback();
    });
  }, (err) => {
    done(totalSizeOfAllFolders);
  });
}

Upvotes: 1

Luca Kiebel
Luca Kiebel

Reputation: 10096

You can use Promise.all here, first construct an array of Promises, and then await all of them calculating the total size:

//const getSize = require('get-folder-size')

let folders = ["C:\\test folder", "C:\\test folder 2\\sub folder"];


function totalFilesizeOfAllFolders(callback) {
  let folderPromises = folders.map(folder => { // use map to create a new array of promises
    return new Promise((resolve, reject) => getSize(folder, (err, size) => {
      if (err) {reject(err)}
      resolve(size);
    }));
  })
  Promise.all(folderPromises) // promise.all waits for all promises in the array to resolve
    .then(sizes => callback(sizes.reduce((a, b) => a + b, 0))); // reduce the array of sizes to a size
}


totalFilesizeOfAllFolders(s => console.log(s)); // => 127



// getsize stub. remove me once you have access to the npm package
function getSize(name, callback) {let sizes = {"C:\\test folder":112, "C:\\test folder 2\\sub folder":15}; callback(null,sizes[name])}

Upvotes: 2

Related Questions