Skip to content

Error using async and await with filereader

I’m trying to read a file using FileReader:

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

        await reader.readAsText(file);
        await this.processFileContent(data);

However, 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?


If you want to do it with promises then you could use the Response constructor (part of fetch api)

async readFile(event) {
  const file =[0]
  if (file) {
    // return this.processFileContent(await file.text())
    const data = await new Response(file).text()


Now it’s possible to just use blob.text() to return a promise that resolves with the text content, doe it’s not available in all browser, see Browser Compatibility@MDN