最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin11浏览0评论

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

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

我有一个从文件中读取日期并将其存储到数组中的函数。它通过异步/等待功能异步实现。问题是它以错误的顺序执行:

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

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

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

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

UPDATE

我已将代码更新为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方法更改为同步方法?

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

回答如下:

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论