使用异步并在FileReader中等待时出错 [英] Error using async and await with filereader

查看:64
本文介绍了使用异步并在FileReader中等待时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用FileReader读取文件:

I'm trying to read a file using FileReader:

async readFile(event: any) {
    var file = event.target.files[0];
    var data:string
    if (file) {   
        var reader:FileReader = new FileReader();
         reader.onload = async function (evt : FileReaderEvent) {
            data = await evt.target.result;
            console.log(evt.target.result);

        };
        console.log(file);
        console.log(data);
        await reader.readAsText(file);
        await this.processFileContent(data);
    }
 }

但是,在我的console.log(file)调用之后,仍然会打印evt.target.result.

However, evt.target.result still gets printed after my console.log(file) call.

有人知道我如何获得文件结果并将其传递给我的processFileContent函数吗?

Does anyone know how I can obtain the result of the file and pass it to my processFileContent function?

推荐答案

如果要使用promises,则可以使用Response构造函数(fetch api的一部分)

If you want to do it with promises then you could use the Response constructor (part of fetch api)

async readFile(event) {
  const file = event.target.files[0]
  if (file) {
    // return this.processFileContent(await file.text())
    const data = await new Response(file).text()
    this.processFileContent(data)
  }
}

更新

现在可以只使用 blob.text()返回一个可以解决文本内容的承诺,但不是在所有浏览器中都可用,请参见

Now it's possible to just use blob.text() to return a promise that resolves with the text content, doe it's not available in all browser, see Browser Compatibility@MDN

这篇关于使用异步并在FileReader中等待时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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