גיא פלד
גיא פלד

Reputation: 39

Return data from function

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

Upvotes: 0

Views: 86

Answers (1)

KiraLT
KiraLT

Reputation: 2607

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

Upvotes: 1

Related Questions