【问题标题】:Synchronicity problem: Wait until multiple fs.readFile calls complete同步问题:等到多个 fs.readFile 调用完成
【发布时间】:2022-02-10 01:07:05
【问题描述】:

我想从不同的 CSV 文件中读取列,并将这些列组合成一个数组。我正在使用fs.readFile 读取CSV 文件和一个回调来处理数据并将一个新元素推送到列数组中。然后将此列数组发送到软件的另一部分(我正在构建一个电子应用程序,因此将其发送到渲染进程)。

我遇到的问题是“fs.readFile”是异步的,所以我的columns 数组在任何fs.readFile 调用完成之前被发送出去,导致一个空数组。

解决此问题的最佳方法是什么?就是简单的使用fs.readFileSync?有没有办法在不阻塞执行的情况下做到这一点?

下面的最小示例代码:

//Process each column, reading the file and extracting the data one at a time
let columns: (number[] | undefined)[] = []; //Somewhere to store the processed columns
for (const dataHandle of dataHandles)
{
  //read the file as a raw string
  fs.readFile(dataHandle.filePath, (error: any, data: any) => {
    if (error) {
      console.log("Error reading file:", error);
    } else {
      data = data.toString();
      const newColumn = parseColumnFromStringDataframe(data, dataHandle.columnName);
      columns.push(newColumn);
    }
  })
}
//Finished processing each column, so send response.
//BUT... readfile is non-blocking! Sends the response before anything is pushed to columns! How can we wait in a smart way?
console.log(columns); // []
mainWindow?.webContents.send("readDataProductColumnsResponse", columns); //Sends response

【问题讨论】:

    标签: node.js typescript asynchronous electron fs


    【解决方案1】:

    此处已回答:https://stackoverflow.com/a/34642827/7603434

    基本上你必须创建一个promise数组然后调用Promise.all(promises);

    const fs = require("fs");
    const files = ["app.js", "index.html", "script.js"];
    
    const readAllFiles = async () => {
      let promises = [];
      for (const f of files) {
        promises.push(fs.promises.readFile(f, "utf8"));
      }
      return Promise.all(promises);
    };
    
    async function run() {
      readAllFiles()
        .then((fileContents) => {
          console.log("done", fileContents);
          // fileContents is an array that contains all the file contents as strings
        })
        .catch((err) => {
          console.error(err);
        });
    }
    
    run();
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2018-04-24
    • 1970-01-01
    • 2017-01-22
    • 2015-10-24
    • 2017-01-23
    相关资源
    最近更新 更多