问题
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