使用异步并在FileReader中等待时出错

布拉泽里克斯

我正在尝试使用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。

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

无尽的

如果您希望通过promises做到这一点,则可以使用Response构造函数(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()返回一个可以解决文本内容的诺言,不是在所有浏览器中都可用,请参见Browser Compatibility @ MDN

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章