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

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是异步的 如何才能实现同步输出呢?

阅读 3.1k
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 等数据异步拿到之后 才渲染那个元素吧。
推荐问题