vue 中出现异步 promise&async 和awiat的使用

一、项目中出现异步问题,接口里边的this.queryLinkage()还未执行完,就开始执行this.$parent.handleShow(this.placeList, this.detailedInformation)

在这里插入图片描述

二、解决办法 new promise()

 // 数组对象去重
       unique(arr) {
        const res = new Map();
        return arr.filter((arr) => !res.has(arr.type) && res.set(arr.type,1));
      },
      // 解决办法:return 出去这个new promise ,在调用queryLinkage()这个方法的时候
       			  使用.then方法,.then中的res返回为true的时候,再去执行
     			  this.$parent.handleShow(this.placeList, this.detailedInformation);
    queryLinkage() {
      let result = new Promise((resolve) => {
      getAlarmCap()
        .then((res) => {
          let algsList = []
          res.data.alarm_type_list.forEach((item) => {
            algsList.push(...item.minor_type);
          });
            this.placeList = this.unique(algsList)
            resolve(true)
        })
        .catch(() => {});
      })
      return result
    },
    //点击方法
  handleOpen(record) {
      this.detailedInformation =  record
      this.placeList = [];
    this.queryLinkage().then(()=>{
        this.$parent.handleShow(this.placeList, this.detailedInformation);
      });
    },

三、补充一下,也可以把这个.then换成async 和await

async handleOpen(record) {
      this.detailedInformation =  record
      this.placeList = [];
      await this.queryLinkage()
      this.$parent.handleShow(this.placeList, this.detailedInformation);
    },

四、try catch

   async queryLinkage() {

try{
  let res = await getAlarmCap()
  let algsList = []
  res.data.alarm_type_list.forEach((item) => {
    algsList.push(...item.minor_type);
  });
    this.placeList = this.unique(algsList)
}catch(err){
  console.log(err)
}
}

五、详细参考

  1. https://blog.csdn.net/weixin_44871749/article/details/123621556?spm=1001.2014.3001.5506
  2. https://blog.csdn.net/weixin_47686269/article/details/109624790?spm=1001.2014.3001.5506

猜你喜欢

转载自blog.csdn.net/weixin_53587375/article/details/129445530
今日推荐