Как связать обещания после линейного потока? - PullRequest
0 голосов
/ 07 сентября 2018

У меня проблема с потоком, я использую обещания сделать это

Контекст такой: пользователь нажимает кнопку, чтобы получить вашу позицию с ионной геолокацией, 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 голосов
/ 07 сентября 2018

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 метода:

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();  
  }
}

И все готово, с хорошим последовательным асинхронным результатом ожидания

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...