Save filereader result to variable for later use

Viewed 408

I can't find simple answer, but my code is simple. I tried something like that, but always when i try to console.log my testResult, then i always recieving null. How to save data from file correctly?

public getFile(
    sourceFile: File
  ): string {
    let testResult;
    const file = sourceFile[0]
    const fileReader = new FileReader();
    fileReader.readAsText(file, "UTF-8")
    fileReader.onloadend = (e) => { 
      testResult = fileReader.result.toString()
    } 
    console.log(testResult)
    return testResult
  }

This problem is related to my other topics, main reason is i can't handle load json file, translate them and upload to user. If i can save this file outside onloadend, then i hope i can handle rest of them (other attempts failed, this one blocking me at beginning)

1 Answers

Your issue is quite classical and is related to the asynchronous operations. Function which you assign to the onloadend request is called only when loadend event fires, but the rest of code will not wait for that to happen and will continue execution. So console.log will be executed immediately and then return will actually return testResult while it is still empty.

Firstly, in order to understand what I just said, put the console.log(testResult) line inside of your onloadend handler:

fileReader.onloadend = (e) => { 
  testResult = fileReader.result.toString();
  console.log(testResult);
}

At this point testResult is not empty and you may continue handling it inside this function. However, if you want your getFile method to be really reusable and want it to return the testResult and process it somewhere else, you need to wrap this method into a Promise, like this:

public getFile(
    sourceFile: File
  ): Promise<string> {
    return new Promise((resolve) => {
      const file = sourceFile[0]
      const fileReader = new FileReader();
      fileReader.onloadend = (e) => { 
        const testResult = fileReader.result.toString();
        resolve(testResult);
      }
      fileReader.readAsText(file, "UTF-8");
    });
  }

Now whereever you need a file you can use the yourInstance.getFile method as follows:

yourInstance.getFile().then(testResult => {
  // do whatever you need here
  console.log(testResult);
});

Or in the async/await way:

async function processResult() {
  const testResult = await yourInstance.getFile();
  // do whatever you need
  console.log(testResult);
}

If you are now familiar with promises and/or async/await, please read more about here and here.

Related