javascript - 递归完成后的操作

标签 javascript node.js recursion

我编写了一个函数,它遍历目录并分析其中的文件,但我不知道如何检测整个过程是否完成(它分析了所有目录和子目录中的所有文件),所以我可以用然后结果。

我使用了递归,但我仍在学习它,我知道它不太正确,所以我想寻求帮助。

const path = require('path');
const fs = require('fs');
const _ = require('lodash');

let result = {};

const goThroughDirs = parentPath => {
    const stat = fs.statSync(parentPath);

    if (stat.isDirectory()) {
        _.each(fs.readdirSync(parentPath), child => goThroughDirs(path.join(parentPath, child)));
    } else {
        analyseFile(parentPath)
            .then(response => {
                result = _.merge({}, result, response);
            });
    }
};

goThroughDirs(path.join(__dirname, 'rootDir'));

提前感谢您的帮助。

最佳答案

鉴于您已经在使用 Promise,它就像这样简单

function goThroughDirs(parentPath) {
    const stat = fs.statSync(parentPath);

    if (stat.isDirectory()) {
        return Promise.all(_.map(fs.readdirSync(parentPath), child =>
//      ^^^^^^ ^^^^^^^^^^^   ^^^
            goThroughDirs(path.join(parentPath, child))
        )).then(responses =>
            _.merge({}, ...responses);
        );
    } else {
        return analyseFile(parentPath);
//      ^^^^^^
    }
}

goThroughDirs(path.join(__dirname, 'rootDir')).then(result => {
    // it's done
    console.log(results);
});

关于javascript - 递归完成后的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43021714/

相关文章:

node.js - Mongoose model.find({}) 使用 mongoose 4.11 后不起作用; [漏洞??]

python - python 查找字符串中的连续字母

java - 异步 Javascript 加载中的挑战

javascript - 检查元素是否具有给定数组中的任何属性

javascript - ES6 - 遍历对象中的键然后分配给新对象

node.js - 对 NodeJS 中的任何请求使用自定义 DNS 解析器

javascript - 使用javascript从MVC Action通过iFrame重定向到父级

node.js - Webpack 找不到模块 ./lib/api/node.js @ multi main

java - 递归求解 A^4 + B^4 + C^4 + D^4 = E^4

scala - 在 Scala 中递归计算平方根