0

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;
  }
גיא פלד
  • 39
  • 1
  • 5

1 Answers1

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);
        };
    });
}
KiraLT
  • 2,385
  • 1
  • 24
  • 36