如何调用函数一次forEach循环完成?

我必须根据条件sorting一些数据,并将其推送到新的数组sortedFiles ,所以基本上一旦forEach循环完成,我想调用asyncFiles()函数并将对象传递给它,但它不会发生在下面的代码。 任何想法是什么实施错误或任何更好的方法来实现这一任务?

filesData是包含目录文件的对象。

ctrl.js

 if (searchObj.searchEnv === 'stat') { stDirectory.readDirectory(function(files) { filesData.logFiles.forEach(function(file) { var sortedFiles = []; var fileDate = new Date(file.fileDate).getTime(); searchStartDate = new Date(searchStartDate).getTime(); searchEndDate = new Date(searchEndDate).getTime(); if (fileDate - searchStartDate > 0 && searchEndDate - fileDate > 0) { console.log('File Date', file); sortedFiles.push(file); } }, function() { console.log(filesData.logFiles); filesData.logFiles = sortedFiles; asyncFiles(filesData); // Not being called. }); }); } 

forEach不是一个采用可选完成callback的asynchronous函数。 只要你的调用后做的东西:

 if (searchObj.searchEnv === 'stat') { stDirectory.readDirectory(function(files){ var sortedFiles = []; // move this in front of the loop filesData.logFiles.forEach(function(file){ var fileDate = new Date( file.fileDate ).getTime(); var searchStartDate = new Date( searchStartDate ).getTime(); // add missing var searchEndDate = new Date( searchEndDate ).getTime(); // `var`s if (fileDate - searchStartDate > 0 && searchEndDate - fileDate > 0) { console.log('File Date',file); sortedFiles.push(file); } }); console.log(filesData.logFiles); filesData.logFiles = sortedFiles; asyncFiles(filesData); // Now being called. }); } 

forEach不以2个函数作为参数。

下面的MDN是forEach函数的语法。

 arr.forEach(function callback(currentValue, index, array) { //your iterator }[, thisArg]); 

所以,第二个function被忽略,没有意义。 因为,你没有在forEach做任何asynchronous操作。 因此,一旦forEach完成,您就可以依靠完成所需的工作,并且在完成forEach函数后可以安全地调用asyncFiles函数。

 if (searchObj.searchEnv === 'stat') { stDirectory.readDirectory(function(files){ filesData.logFiles.forEach(function(file){ var sortedFiles = []; var fileDate = new Date( file.fileDate ).getTime(); searchStartDate = new Date( searchStartDate ).getTime(); searchEndDate = new Date( searchEndDate ).getTime(); if (fileDate - searchStartDate > 0 && searchEndDate - fileDate > 0) { console.log('File Date',file); sortedFiles.push(file); } }); console.log(filesData.logFiles); filesData.logFiles = sortedFiles; asyncFiles(filesData); // Not being called. }); } 

从你的代码示例asyncFiles不会被调用,因为forEach需要1个参数不是2,但如果你想在forEach循环之后调用一个正在做asynchronous调用的函数,那么你可以在asynchronous库中使用map函数。

https://caolan.github.io/async/docs.html#map

 async.map(filesData.logFiles, (logFile, next) => { // Do some work with logFile next(); }, (err, results) => { // Call function after mapping is complete });