Home > Software design >  how can i store callback function's value to vue data
how can i store callback function's value to vue data

Time:11-13

#i can't log this.zuobiao after i used the function which is given value to this.zuobiao, why?

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
     }
   });
}

i used async await but not work , promise.then is also, how to store res.result.address to this.zuobiao

CodePudding user response:

showAddress is asynchronous, so its result won't be available when the console.log happens. Promises are the right way to go. Here's some help on using them...

Make promise-returning async functions that perform the API generically...

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 });
  });
}

With these, the calling function is simple...

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
  });
}
  • Related