无法在循环中添加函数的结果

时间:2018-08-31 10:42:38

标签: javascript

我有此功能getSize()(来自npm模块:get-folder-size),该功能用于计算文件夹(目录)中所有文件的总大小。

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 
}

问题

如何正确遍历数组folders并求和计算数组中所有文件夹的size?我不确定如何从函数中返回size

2 个答案:

答案 0 :(得分:2)

您可以在此处使用Promise.all,首先构造一个Promises数组,然后等待所有它们计算总大小:

//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])}

答案 1 :(得分:1)

您可以使用Async之类的库来帮助您异步迭代调用,然后将回调传递给函数以返回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);
  });
}