异步/等待功能无法正常工作

时间:2019-10-08 15:54:50

标签: javascript node.js asynchronous

我有一个函数,可以从文件中读取日期并将其存储到数组中。 它通过异步/等待功能异步实现。

问题在于它以错误的顺序执行:

const util = require('util');
const fs = require('fs');
const path = require('path');

const readFile = util.promisify(fs.readFile);
const readDirectory = util.promisify(fs.readdir);

// Retrieve logs from logs files and store them into an array
const getAuditLogsData = async () => {
    const logsFolderPath = path.join(__dirname, '../', 'logs');
    const logData = [];

    try {
        const files = await readDirectory(logsFolderPath);
        // 1ST - OK
        console.log(files);
        files.forEach(async (file) => {

            const content = await readFile(logsFolderPath + '/' + file, 'utf-8');
            const logList = JSON.parse(content);

            logList.forEach((log) => {
                // 4TH - NOT OK
                console.log(1)
                logData.push(log);
            });

        });
        // 2ND - NOT OK
        console.log(2);
    } catch (error) {
        console.log(error);
    }

    // 3RD - NOT OK, EMPTY ARRAY (deta is 100% pushing in the forEach loop)
    console.log(logData);

    return logData;
};

module.exports = {
    getAuditLogsData
};

异步/等待承诺有问题吗?

更新

我已将代码更新为for-of循环,但仍然无法正常工作:

try {
    const files = await readDirectory(logsFolderPath);
    // 1ST - OK
    console.log(files);

    for (const file of files) {
        const content = await readFile(logsFolderPath + '/' + file, 'utf-8');
        const logList = JSON.parse(content);

        logList.forEach((log) => {
            // 4TH - NOT OK
            console.log(1);
            // console.log(log);
            logData.push(log);
            // console.log(logData);
        });
    }

    // 2ND - NOT OK
    console.log(2);
} catch (error) {
    console.log(error);
}

我可以将fs方法更改为同步方法吗?

您能告诉我这段代码的错误在哪里吗?

1 个答案:

答案 0 :(得分:1)

尝试await Promise.all(files.map(async _ => {...})),但请记住,.all会在第一次失败时拒绝。