在回调函数中访问数据

时间:2018-05-02 14:03:17

标签: javascript angular google-maps typescript google-geocoder

我有一个地址编码功能,该地址返回同一地址的城市名称

  // geocode the given address
  geocodeAddress(address, callback) {
    this.mapsAPILoader.load().then(() => {
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          results[0].address_components.forEach(arrAddress => {
            if (arrAddress.types[0] == "locality") {
              callback(arrAddress.long_name);
            }
          })
        } else {
          console.log("Geocode was not successful for the following reason: " + status);
        }
      });
    });
  };

当我调用该功能并想要打印城市名称时,它会被打印并且未定义'从geocodeAddress函数下面的代码行开始,然后正确打印城市名称

this.geocodeAddress(this.offerAddress, data => {
  this.hostCity = data;
  console.log(this.hostCity);
});
console.log(this.hostCity);

我试图在第二个console.log函数之前添加一些超时但没有任何成功

因此,我对从地理编码器返回数据后如何访问此值感兴趣,因为我需要使用此数据存储在数据库中,如果我尝试像这样存储

    this.geocodeAddress(this.offerAddress, data => {
            this.hostCity = data;
            this.service.addData({"address": this.offerAddress, "city": this.hostCity}, "/data")
                .subscribe(data => {
                  this.router.navigate(['list']);
                })
          });

它存储数据但router.navigate无法正常工作

所以我需要在geocodeAddress回调函数之外访问hostCity的解决方案,或者如何正确调用此geocodeAddress回调函数中的其他函数

1 个答案:

答案 0 :(得分:1)

如果您正在使用TypeScript,则可以使geocodeAddress方法返回Promise,而不是使用回调,然后使用async/await

async geocodeAddress(address): Promise<string[]> {
    return new Promise((resolve, reject) => {
        this.mapsAPILoader.load().then(() => {
           var geocoder = new google.maps.Geocoder();
           geocoder.geocode({ 'address': address }, function (results, status) {
               if (status == google.maps.GeocoderStatus.OK) {
                   const result: string[] = [];
                   results[0].address_components.forEach(arrAddress => {
                       if (arrAddress.types[0] == "locality") {
                           result.push(arrAddress.long_name);
                       }
                   });
                   resolve(results);
               } else {
                   console.log("Geocode was not successful for the following reason: " + status);
                   reject(status);
               }
           });
       });
    });
};

现在,此函数返回一个数组,其中包含您要查找的所有地址的长名称。使用它:

const data: string[] = await this.geocodeAddress(this.offerAddress);
this.hostCity = data[0];
// do whatever you want now

通过这种方式,您可以获得异步编程的优势,并且具有同步编程的简单性。