如何在JavaScript中使用FileReader.readAsText同步读取文件?

How to read file using FileReader.readAsText synchronously in JavaScript?

我正在尝试使用 JavaScript 中的 FileReader.readAsText() 读取 CSV 文件。但我无法同步获取价值。我尝试了多种方法。但是 none 正在工作。以下是我目前的代码:

第一种方法:

<input
id = "inputfile"
type = "file"
name = "inputfile"
onChange = {uploadFile} >
    const uploadFile = (event: React.ChangeEvent < HTMLInputElement > ) => {
        let resultSyncOutput = '';

        connst files = event?.target.files;

        if (files && files.length > 0) {
            readAsTextCust(files[0]).then(resultStr => {
                resultSyncOutput = resultStr;
            });
        }
      
      // At this line I am not able to get the value of resultSyncOutput with the content of file sychronously
      
      //Do something with the result of reading file.
      someMethod(resultSyncOutput);
    }

async function readAsTextCust(file) {
    let resultStr = await new Promise((resolve) => {
        let fileReader = new FileReader();
        fileReader.onload = (e) => resolve(fileReader.result);
        fileReader.readAsText(file);
    });

    console.log(resultStr);

    return resultStr;
}

这是我尝试的第一种方法,即使用 async/await。我也尝试在没有 aysnc/await 的情况下这样做,但仍然无法成功。此操作的同步性至关重要。项目中也不允许使用 Ajax。

注意:我在 Stack Overflow 中检查了很多答案,none 提供了解决此问题的方法。所以请不要将其标记为重复。任何地方都没有提供这个特定问题的答案。

即使这对你来说很简单,也请帮助我

您需要为onload事件回调设置一个回调函数来获取结果。另请注意,您需要对上传的 CSV 文件调用 readAsText

您可以这样在输入的 onChange 回调中使用 FileReader API:

<input
id = "inputfile"
type = "file"
name = "inputfile"
onChange = function (event: React.ChangeEvent<HTMLInputElement>) {
    const reader = new FileReader();

    reader.onload = (e) => {
        console.log(e.target?.result) // this is the result string.
    };

    reader.readAsText(event.target.files?.[0] as File);
  };

也不需要 async/await。

我找到了解决方案 resultSyncOutput = await readAsTextCust(files[0]);并将调用函数声明为异步有效。