Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using async and await with filereader

I'm trying to read a file using FileReader:

async readFile(event: any) {
    var file = event.target.files[0];
    var data:string
    if (file) {   
        var reader:FileReader = new FileReader();
         reader.onload = async function (evt : FileReaderEvent) {
            data = await evt.target.result;
            console.log(evt.target.result);

        };
        console.log(file);
        console.log(data);
        await reader.readAsText(file);
        await this.processFileContent(data);
    }
 }

However, evt.target.result still gets printed after my console.log(file) call.

Does anyone know how I can obtain the result of the file and pass it to my processFileContent function?

like image 701
blazerix Avatar asked Jan 09 '18 16:01

blazerix


People also ask

Is Javascript FileReader async?

Understanding FileReaderThe FileReader methods work asynchronously but don't return a Promise. And attempting to retrieve the result immediately after calling a method will not work, as the . onload event handler fires only after the FileReader has successfully finished reading the file and updates the FileReader's .


1 Answers

Use the new read methods on the blob itself

/** @type {Event} evt */
async readFile (evt) {
  const [file] = evt.target.files
  if (!file) return
  const data = await file.text()
  return this.processFileContent(data)
}

Alternative:

evt.target.files[0]?.text().then(this.processFileContent)
like image 112
Endless Avatar answered Oct 01 '22 02:10

Endless