如何将回调函数的值存储到vue数据

5sxhfpxr  于 2022-11-17  发布在  Vue.js
关注(0)|答案(1)|浏览(126)

我不能记录这个.zuobiao在我使用了这个函数的赋值之后.zuobiao,为什么?

getUserProfile() {
 uni.getLocation({
  type: 'gcj02 ',
  geocode: true,
  success: (res) => {
   this.showAddress(res.longitude,res.latitude)
   console.log(this.zuobiao); // this.zuobiao is empty, why?
   uni.showModal({
    content: '坐标:' + this.zuobiao
   })
  }
 });
},
 showAddress(longitude, latitude) {
   const qqmapsdk = new QQMapWX({
      key: 'PU7BZ-42SKX-SVF4G-PE7K2-ZMFD7' //此处使用你自己申请的key  
   });
   // 腾讯地图调用接口  
   qqmapsdk.reverseGeocoder({
     location: {
      latitude: latitude,
      longitude: longitude
     },
     success: (res) => {
      this.zuobiao = res.result.address // already get value
     }
   });
}

我用了异步等待,但不工作,承诺。然后也是,如何存储res。result。地址到这个。zuobiao

t5zmwmid

t5zmwmid1#

showAddress是异步的,所以当console.log发生时,它的结果将不可用。承诺是正确的方法。下面是一些使用它们的帮助...
使返回承诺的异步函数以通用方式执行API ...

async getLocation(type, geocode) {
  // to do: error handling
  return new Promise(resolve => {
    const success = res => resolve(res); // res is an object with lat/long props
    uni.getLocation({ type, geocode, success });
  });
}

async reverseGeocoder(location) {
  const qqmapsdk = new QQMapWX({
    key: 'PU7BZ-42SKX-SVF4G-PE7K2-ZMFD7' //此处使用你自己申请的key  
  });
  return new Promise(resolve => {
    const success = res => resolve(res.result.address);
    qqmapsdk.reverseGeocoder({ location, success });
  });
}

有了这些,调用函数就简单了......

async getUserProfile() {
  const location = await this.getLocation('gcj02 ', true);
  this.zuobiao = await this.reverseGeocoder(location);
  console.log(this.zuobiao); // this.zuobiao should be initialized
  uni.showModal({
    content: '坐标:' + this.zuobiao
  });
}

相关问题