vue中reader.onload读取文件的异步问题

问题

用element上传文件组件上传文件,然后在前端读取,由于reader.onload读取文件是异步的会造成return回去的数据无法被获取

export function import_excel_to_json(file){
    let jsonData = {}
    let reader = new FileReader()
    reader.readAsArrayBuffer(file)
    reader.onload =  function () {
        let buffer = reader.result
        let bytes = new Uint8Array(buffer)
        let length = bytes.byteLength
        let binary = ''
        for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
        }
        let XLSX = require('xlsx')
        let wb = XLSX.read(binary, {
            type: 'binary'
        })
        wb.SheetNames.map(item=>{
          jsonData[item] = XLSX.utils.sheet_to_json(wb.Sheets[item])
          jsonData[item].shift()
        })
        return jsonData
    }
  })
}

在外部调用该函数:

let data = this.import_excel_to_json(File)

data获取不到返回值

解决

用Promise进行处理

export function import_excel_to_json(file){
  return new Promise(function (resolve, reject) {
    let jsonData = {}
    let reader = new FileReader()
    reader.readAsArrayBuffer(file)
    reader.onload =  function () {
        let buffer = reader.result
        let bytes = new Uint8Array(buffer)
        let length = bytes.byteLength
        let binary = ''
        for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
        }
        let XLSX = require('xlsx')
        let wb = XLSX.read(binary, {
            type: 'binary'
        })
        wb.SheetNames.map(item=>{
          jsonData[item] = XLSX.utils.sheet_to_json(wb.Sheets[item])
          jsonData[item].shift()
        })
        resolve(jsonData);
    }
  })
}
Logo

前往低代码交流专区

更多推荐