Return data from function

£可爱£侵袭症+ 提交于 2021-01-29 07:40:18

问题


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;
  }

回答1:


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

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);
        };
    });
}


来源:https://stackoverflow.com/questions/64587264/return-data-from-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!