从函数返回数据 [英] Return data from function

查看:68
本文介绍了从函数返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从reader.onload函数返回数据(csvData).我希望数据将从readCsv函数返回:

How can I return the data (csvData) from the reader.onload function. I want that the data will return from readCsv function:

 async readCSV(event) {
    const reader = new FileReader();
    reader.readAsText(event.target.files[0]);
    var csvToJson;
    csvToJson = reader.onload = async () => {
      const text = reader.result;
      const csvData =  await this.csvJSON(text);
      return csvData;
    };
    return csvToJson;
  }

推荐答案

我看到您已经在使用 async 语法.异步语法会自动将所有内容包装到 Promise 实例

I see that you already using async syntax. Async syntax automatically wraps everything to Promise instance.

但是您还可以返回承诺手动实例.它使用 resolve &接受回调拒绝参数.您可以调用 resolve 来解决承诺.

But you also can return Promise instance manually. It accepts callback with resolve & reject arguments. And you can call resolve to resolve the promise.

async function readCSV(event) {
    return new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsText(event.target.files[0]);
        reader.onload = async () => {
            const text = reader.result;
            const csvData =  await this.csvJSON(text);
            resolve(csvData);
        };
    });
}

这篇关于从函数返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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