FileReader readAsText() async issues?

前端 未结 3 2083
忘掉有多难
忘掉有多难 2021-01-12 22:29

I have implemented the following code to parse a CSV via a selection:

export async function parse(file: File) {
           


        
相关标签:
3条回答
  • 2021-01-12 23:07

    To generalize @zero298's answer a tiny bit, here's the generic Promise-based wrapper around FileReader -

    // get contents of a file as obtained from an html input type=file element
    function getFileContents(file) {
      return new Promise((resolve, reject) => {
        let contents = ""
        const reader = new FileReader()
        reader.onloadend = function (e) {
          contents = e.target.result
          resolve(contents)
        }
        reader.onerror = function (e) {
          reject(e)
        }
        reader.readAsText(file)
      })
    }
    

    used like so -

    async function parse(file) {
      const contents = await getFileContents(file)
      const result = contents.split(/\r\n|\n/)
      return result
    }
    

    or in the general case,

    async function show(file) {
      const contents = await getFileContents(file)
      alert(contents)
    }
    
    0 讨论(0)
  • 2021-01-12 23:22

    Here is the JSBin I have tried and it work like a charm.

    function parse(file) {
      const reader = new FileReader();
      reader.readAsText(file);
      reader.onload = function(event) {
        // The file's text will be printed here
      console.log(reader.result)
      }
    }
    

    Updated:

    I write you a Promise version.

    async function parse(file) {
      const reader = new FileReader();
      reader.readAsText(file);
      const result = await new Promise((resolve, reject) => {
        reader.onload = function(event) {
        resolve(reader.result)
        }
      })
      console.log(result)
    }
    
    0 讨论(0)
  • 2021-01-12 23:30

    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);
      });
    }
    
    0 讨论(0)
提交回复
热议问题