如何在线性流之后链接承诺?

时间:2018-09-07 08:04:48

标签: javascript angular typescript ionic-framework promise

我的流程有问题,我正在使用诺言做到这一点

上下文是:用户单击以获取离子地理位置的位置,ir返回lat和log,然后我要解码坐标以获取City,最后一步将lat,long和city设置为用户。

tryGeolocation() {       
    this.geolocation.getCurrentPosition().then((resp) => {
      let pos = {
        lat: resp.coords.latitude,
        lng: resp.coords.longitude
      };
      this.lat = resp.coords.latitude;
      this.long = resp.coords.longitude;          
      console.log(this.lat+"--"+this.long);
      this.decodeCoord(this.lat, this.long);
      alert(this.city);
      this.uploadLocation();    
    }).catch((error) => {
      console.log('Error getting location', error);
      this.loading.dismiss();
    });
  }



 decodeCoord(lat, long) {    
    console.log("decodeCoord");
    var latlng = new google.maps.LatLng(lat, long);
    this.geocoder.geocode({'latLng': latlng}, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {       
        if (results[1]) {
          var indice = 0;
          for (var j = 0; j < results.length; j++) {
            if (results[j].types[0] == 'locality') {
              indice = j;
              break;
            }
          }   

          let city, region, country;
          for (var i = 0; i < results[j].address_components.length; i++) {
            if (results[j].address_components[i].types[0] == "locality") {
              //this is the object you are looking for City
              city = results[j].address_components[i];
            }
            if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
              //this is the object you are looking for State
              region = results[j].address_components[i];
            }
            if (results[j].address_components[i].types[0] == "country") {
              //this is the object you are looking for
              country = results[j].address_components[i];
            }
          }
          //city data        
          this.city=city;
        } else {
          console.log("No results found");
        }           
      } else {
        console.log("Geocoder failed due to: " + status);
      }
    });      
  }



uploadLocation() {   
    let position = {
      latitude: this.lat,
      longitude: this.long,
      city: this.city
    }  
    this._us.updateUserIndividual(position).then(data => {      
      console.log("USER UPDATED");
    }).catch((err) => {
      this.presentToast("Ups! Ha ocurrido un Error, intentalo otra vez");
    })
  }

我尝试添加this.decodeCoord(this.lat,this.long);在uploadLocation上,但它也不起作用。

城市永远是空的。

1 个答案:

答案 0 :(得分:1)

this.city为空,因为您是在单独的this上下文中进行分配的。您在定义this.geocoder.geocode()时创建了这个新上下文,并使用function关键字创建了回调函数。用箭头功能替换它,我想您再也可以了:

this.geocoder.geocode({'latLng': latlng}, (results, status) => {
  // ...
});

但是我不能再犯错了。

this.decodeCoord(this.lat, this.long);
alert(this.city);

那是行不通的。顾名思义,因为我更改的回调函数是一个异步函数。因此,您最好的办法是从Promise方法返回一个decodeCoord

decodeCoord(lat, long) {    
  return new Promise((resolve, reject) => {
    // ...
    this.geocoder.geocode({'latLng': latlng}, (results, status) => {
      if (status == google.maps.GeocoderStatus.OK) { 
        // ...
        resolve();
      } else {
        reject();
      }
    });
  });
}

然后您甚至还没有到那儿,还需要从updateLocation方法中返回promise:

return this._us.updateUserIndividual(position).

然后,您可以更改tryGeolocation方法:

async tryGeolocation() {   
  try {
    const { coords } = await this.geolocation.getCurrentPosition();
    this.lat = coords.latitude;
    this.long = coords.longitude;          

    await this.decodeCoord(coords.latitude, coords.longitude);
    alert(this.city);
    await this.uploadLocation(); 
  } catch (e) {
    console.log('Error getting location', e);
  }  finally {
    this.loading.dismiss();  
  }
}

您已经完成,并获得了不错的顺序异步等待结果