javascript - 递归异步到 promise 或回调

标签 javascript node.js asynchronous callback promise

问题: 我有一个棘手的情况,我正在递归遍历文件和目录,当文件符合特定条件时,我使用 Node 的 readLine(异步函数)读取该文件的第一行。一旦该行被读取,条目就会被插入一个变量(例如 depTree)。由于我的一些代码是异步的,所以我无法同步获取 depTree 的值。

代码:

const fs = require('fs'); 
const readline = require('readline');
const path = './mycoolpath/';
const depTree = [];

const imports = file => {
    const readLines = readline.createInterface({
        input: fs.createReadStream(file),
        crlfDelay: Infinity
    });
    // read each line, and push line to depTree if it passes my regex criteria
    readLines.on('line', (line) => {
        if (/lineMatchesMyregex/.test(line)) {
            depTree.push(line)
        }
    });
}

const recursiveSearch = path => {
    const files = fs.readdirSync(path);
    for (var i in files) {
        var file = path + '/' + files[i];
        var stats = fs.statSync(file);
        if (stats.isFile()) {
            imports(file);
        }
        else if (stats.isDirectory()) {
            recursiveSearch(file);
        }
    }

};

recursiveSearch(path);

//// embaressing setTimeout
// setTimeout(() => {
//     console.log(depTree)
// }, 1000) 

尝试:

我不得不使用 setTimeout 并且我确信有更好的方法,我修改了回调和 promise 但无济于事。如果有任何帮助/见解,我将不胜感激。

最佳答案

如果您在 Node.js 中使用 async/await 关键字和 promises,您可以按如下方式解决此问题:

const fs = require('fs');
const readline = require('readline');
const path = './mycoolpath/';
const depTree = [];

const imports = file => {
    return new Promise((resolve, reject) => {
        const readLines = readline.createInterface({
            input: fs.createReadStream(file),
            crlfDelay: Infinity
        });
        // read each line, and push line to depTree if it passes my regex criteria
        readLines.on('line', (line) => {
            if (/lineMatchesMyregex/.test(line)) {
                depTree.push(line)
            }
        });
        // once done reading all the lines, resolve the promise
        readLines.on('close', () => {
            resolve();
        })
    });
}

const recursiveSearch = async (path) => {
    const files = fs.readdirSync(path);
    for (var i in files) {
        var file = path + '/' + files[i];
        var stats = fs.statSync(file);
        if (stats.isFile()) {
            await imports(file);
        } else if (stats.isDirectory()) {
            await recursiveSearch(file);
        }
    }

};


//// embaressing setTimeout
setTimeout(async () => {
    await recursiveSearch(path);
    console.log(depTree)
}, 1000)

// or even better, to avoid too long or too short timeout
recursiveSearch(path)
    .then(() => {
        console.log(depTree)
    })

关于javascript - 递归异步到 promise 或回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52651882/

相关文章:

javascript - 以 Base 64 读取文件并将其存储到状态变量中

java - 如何使用 Unirest 等待所有异步 REST 调用完成?

php - 如何在 javascript 中获取表单元素值并使用这些值创建 url

node.js - 更改nodejs-ubuntu的系统版本

node.js - 使用nodejs发送Firebase通知

javascript - Array.prototype.slice.appy(arguments, 1) 的问题

javascript - Backbone JS 路由无法正常工作

java - 在非 native 应用程序中将号码添加到 iPhone 或 Android 手机联系人列表

javascript - 背景位置上的 Jquery + ccs3 转换

javascript - 通过简单示例轻描淡写 Node.js 异步