#我用了赋予this.zubiao值的函数后,无法记录this.zubiao,为什么?

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  
   });
   // 腾讯 map 调用接口  
   qqmapsdk.reverseGeocoder({
     location: {
      latitude: latitude,
      longitude: longitude
     },
     success: (res) => {
      this.zuobiao = res.result.address // already get value
     }
   });
}

我用了异步等待而不是工作,promise .然后也是,如何存储res.Result.Address to this.zubiao

推荐答案

showAddress是异步的,所以当console.log发生时,它的结果将不可用.promise 才是正确的道路.这里有一些关于使用它们的帮助.

使promise 返还的异步函数执行一般的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
  });
}

Javascript相关问答推荐

为什么!逗号和空格不会作为输出返回,如果它在参数上?

Chromium会将URL与JS一起传递到V8吗?

Angular 订阅部分相互依赖并返回数组多个异步Http调用

当我try 将值更改为True时,按钮不会锁定

使用插件构建包含chart.js提供程序的Angular 库?

为列表中的项目设置动画

处理TypeScrip Vue组件未初始化的react 对象

ngOnChanges仅在第二次调用时才触发

是否可以在不更改组件标识的情况下换出Reaction组件定义(以维护状态/引用等)?如果是这样的话,是如何做到的呢?

为什么NULL不能在构造函数的.Prototype中工作

是否设置以JavaScript为背景的画布元素?

如何使用puppeteer操作所有选项

使用Perl Selify::Remote::Driver执行Java脚本时出错

使用Java脚本替换字符串中的小文本格式hashtag

如何格式化API的响应

在AgGrid中显示分组行的单元格值

使用重新 Select 和对象理解 Select 器备忘

JQuery-无法 Select 使用elementor添加的元素的值

JS:以特定格式显示不同时区

如何用JAVASCRIPT更新背景位置值来实现CSS视差滚动?