将文件夹的每个文件加载为 json 数组

loading each file of a folder as json array

我在文件系统上有一个包含 JSON 个文件的文件夹。现在我试图将每个 JSON 文件加载到一个工作正常的对象中。当我尝试将每个对象推入数组时,问题就开始了。我的 loadJSONFolderFiles() 只有 returns 一组承诺。

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;
}

因为你正在将承诺推入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;
}