如何让回调函数同步输出结果?

getLocation(lng,lat){
                let city = '';
                new BMap.Geocoder().getLocation(new BMap.Point(this.parse(lng), this.parse(lat)), rs => {
                    city = rs.addressComponents.city;
                });
                return city;
            }

函数不能实时输出city 因为getlocation是异步的 如何才能实现同步输出呢?

阅读 2.9k
2 个回答

用Promise ,方法如下:

getLocation(lng,lat){
   return new Promise(function(resolve, reject){
          let city = '';
          new BMap.Geocoder().getLocation(new BMap.Point(this.parse(lng), this.parse(lat)), rs => {
              city = rs.addressComponents.city;
              resolve(city);
          });
     });
}

//使用

getLocation(lng,lat).then(function(city){
  console.log(city);
})

如果帮到你,希望采纳,谢谢

看到bind里面用的话,应该是不行的。 建议还是v-if 等数据异步拿到之后 才渲染那个元素吧。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题