Search code examples
javascripthtmltypescript

FileReader readAsText() async issues?


I have implemented the following code to parse a CSV via a <input type="file" /> selection:

export async function parse(file: File) {
  let content = '';
  const reader = new FileReader();
  reader.onload = function(e: any) {
    content = e.target.result;
  };
  await reader.readAsText(file);
  const result = content.split(/\r\n|\n/);
  return result;
}

If I run this code and put a breakpoint on the line where I declare result, it retrieves the contents of the file successfully. If I do not put any breakpoint, the content is empty. As you can see, I added await to the line where the reader reads the file as text, but it's still not working.


Solution

  • await doesn't help here. readAsText() doesn't return a Promise.

    You need to wrap the whole process in a Promise:

    export function parse(file: File) {
      // Always return a Promise
      return new Promise((resolve, reject) => {
        let content = '';
        const reader = new FileReader();
        // Wait till complete
        reader.onloadend = function(e: any) {
          content = e.target.result;
          const result = content.split(/\r\n|\n/);
          resolve(result);
        };
        // Make sure to handle error states
        reader.onerror = function(e: any) {
          reject(e);
        };
        reader.readAsText(file);
      });
    }