我在文件系统上有一个JSON文件夹。现在我尝试将每个JSON文件加载到一个工作正常的对象中。当我尝试将每个对象推入数组时,问题就开始了。我的 loadJSONFolderFiles()只返回一个promises数组。
function loadJSONFolderFiles(p_path) {
var deferred = Q.defer();
var subfiles = [];
fs.readdir(p_path, function (err, files) {
if (err) {
return rxError("internal", 2002, "could not read folder");
}
files.forEach(function (subfile) {
var deferredLink = Q.defer();
var folderFilePath = p_path + "/" + subfile;
console.log("accessing " + folderFilePath);
// loadJSONFile() tested and works fine
loadJSONFile(folderFilePath).then(function (p_file) {
console.log("adding file " + folderFilePath);
deferredLink.resolve(p_file);
});
subfiles.push(deferredLink.promise);
});
deferred.resolve(subfiles);
});
return deferred.promise;
}
答案 0 :(得分:1)
因为 将承诺推送到subfiles
数组。
这是一个简单的修复。它在运行时可能会出错,但是如果遇到问题,至少应该更容易修复它们:
function loadJSONFolderFiles(p_path) {
var deferred = Q.defer();
var subfiles = [];
fs.readdir(p_path, function (err, files) {
if (err) {
return rxError("internal", 2002, "could not read folder");
}
var total = files.length;
files.forEach(function (subfile) {
//var deferredLink = Q.defer();
var folderFilePath = p_path + "/" + subfile;
console.log("accessing " + folderFilePath);
// loadJSONFile() tested and works fine
loadJSONFile(folderFilePath).then(function (p_file) {
console.log("adding file " + folderFilePath);
//deferredLink.resolve(p_file);
subfiles.push(p_file);
if(subfiles.length === total) {
deferred.resolve(subfiles);
}
});
});
//deferred.resolve(subfiles);
});
return deferred.promise;
}