我确信这是一个相当简单的任务,但我现在无法全神贯注。我有一组嵌套的 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);
}
Using forEach
的第二个参数,索引,可以在每次运行最内层循环时检查是否所有循环都完成。
因此,只需在代码中添加几行即可得到:
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);
}
});
});
});
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)