我这里是使用文件上传的场景,

主要关键字 await async 进行同步阻塞,然后,就可以在循环中,等待响应后,在进行调用
如果不等待,则前端会一次性将循环体遍历完,请求直接占满,导致其他功能请求,会阻塞,受到影响
async fnUploadDocFileForBatchOrder(data) {
      return uploadDocFileForBatchOrder(data); // js 调用的后端方法
    },
    async fnUploadDocFileForOrder(data) {
      return uploadDocFileForOrder(data); // js 调用的后端方法
    },
    async uploadIma(i) {
      let cc;
      console.log("总文件数:" + this.fileList.length + "==当前第" + i + "个");
      if (i >= this.fileList.length) {
        return false;
      }
      let fd = new FormData();
      fd.append("file", this.fileList[i].raw);
      this.uploadForm.fileList = fd;
      if (this.upload.title == "单个订单数据导入") {
        cc = await this.fnUploadDocFileForOrder(this.uploadForm);
      } else {
        cc = await this.fnUploadDocFileForBatchOrder(this.uploadForm);
      }
      // console.log(JSON.stringify(cc));
     // 这里控制循环体是否结束
      if (cc != undefined && cc.code != undefined) {
        return true;
      }
      return false;
    },
    // 提交上传文件
    async submitFileForm() {
      if (this.fileList.length == 0) {
        this.$message.error("请上传文件");
        return false;
      }
      if (
        this.uploadForm.fileSource == undefined ||
        this.uploadForm.fileSource.length == 0
      ) {
        this.$message.error("请选择文件来源");
        return false;
      }
      if (
        this.uploadForm.orderType == undefined ||
        this.uploadForm.orderType.length == 0
      ) {
        this.$message.error("请选择订单类型");
        return false;
      }
      if (this.upload.title == "单个订单数据导入") {
        if (
          this.uploadForm.code == undefined ||
          this.uploadForm.code.length == 0
        ) {
          this.$message.error("请输入单号");
          return false;
        }
      }

      this.upload.open = false;
      this.msgSuccess("数据上传中,已转入后台处理,请不要关闭浏览器");
      this.buttenloading = true;
      this.getList();
      this.progressshow = true;
      let flag = true;
      let index = 0;
      while (flag) {
        // 进度条变量
        this.progressd = parseInt((index / this.fileList.length) * 100);
        flag = await this.uploadIma(index);
        index++;
      }
      this.buttenloading = false;
      this.progressshow = false;
      this.fileList = [];
      this.$refs.upload.submit();
    },

js 方法文件

// 批量上传单据
export function uploadDocFileForBatchOrder(data) {
    return request({
        url: `/docfile/uploadDocFileForBatchOrder?orderType=${data.orderType}&fileSource=${data.fileSource}`,
        method: 'post',
        // headers: { 'Content-Type': 'multipart/form-data' },
        data: data.fileList
    })
}

export function uploadDocFileForOrder(data) {
    return request({
        url: `/docfile/uploadDocFileForOrder?code=${data.code}&orderType=${data.orderType}&fileSource=${data.fileSource}`,
        method: 'post',
        data: data.fileList
    })
}
Logo

前往低代码交流专区

更多推荐