FileReader readAsText()异步问题? [英] FileReader readAsText() async issues?

查看:1089
本文介绍了FileReader readAsText()异步问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了以下代码,通过< input type =file/> 选择来解析CSV:

I have implemented the following code to parse a CSV via a <input type="file" /> selection:

export async function parse(file: File) {
  let content = '';
  const reader = new FileReader();
  reader.onload = function(e: any) {
    content = e.target.result;
  };
  await reader.readAsText(file);
  const result = content.split(/\r\n|\n/);
  return result;
}

如果我运行此代码并在我声明的行上放置一个断点结果,它成功检索文件的内容。如果我没有放置任何断点,则内容为空。正如您所看到的,我将等待添加到读者将文件作为文本读取的行,但它仍然无效。

If I run this code and put a breakpoint on the line where I declare result, it retrieves the contents of the file successfully. If I do not put any breakpoint, the content is empty. As you can see, I added await to the line where the reader reads the file as text, but it's still not working.

推荐答案

await 在这里没有帮助。 readAsText()不返回承诺

await doesn't help here. readAsText() doesn't return a Promise.

您需要将整个过程包装在承诺

You need to wrap the whole process in a Promise:

export function parse(file: File) {
  // Always return a Promise
  return new Promise((resolve, reject) => {
    let content = '';
    const reader = new FileReader();
    // Wait till complete
    reader.onloadend = function(e: any) {
      content = e.target.result;
      const result = content.split(/\r\n|\n/);
      resolve(result);
    };
    // Make sure to handle error states
    reader.onerror = function(e: any) {
      reject(e);
    };
    reader.readAsText(file);
  });
}

这篇关于FileReader readAsText()异步问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆