js在onload中拿到返回值

js的文件读取onload函数没办法直接返回值,但是有很多时候我们又需要返回一个在处理后的值。实现方法是传递一个绑定了this的回调函数

const callback = (result)=>{//定义回调函数
        this.result = result
        console.log(this.result)
      }
      file_name = this.selectFile.name;
      if(!file_name.match(reg)){
        console.error('the file chosed must be a image')
        return
      }
      if (file_name) {
      getTextFromImage(this.selectFile,callback.bind(this))//绑定this很重要,防止this丢失;
     
      } else {
        console.warn("the file not existed");
      }


//getTextFromImage
export   function  getTextFromImage(file,callback){
   
    var reader = new FileReader()

    reader.readAsArrayBuffer(file) // 读取成二进制
    
    reader.onload = async function () {
        var fileData = this.result

       
        var appId = '726fc'
        
        var secretCode = '1ea026885'
      
        var url = 'https://api.textin.com/robot/v1.0/api/text_recognize_3d1'
       
   
   //axios.post/get返回的才是promise
   let result = await  axios.post(url,{data:fileData},{headers:{'x-ti-app-id':appId,'x-ti-secret-code': secretCode}})
   callback(result)
    }
  
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值