Home > Back-end >  async and await method in typescript (angular)
async and await method in typescript (angular)

Time:09-17

I have two functions and whenever I call them in ngOninit the second one always gets called before the other could someone explain how can I use async/await in such case with a clear and simple example

getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position: Position) => {
        if (position) {
          console.log("Latitude: "   position.coords.latitude  
            "Longitude: "   position.coords.longitude);
          this.lat = position.coords.latitude;
          this.lng = position.coords.longitude;
          console.log(this.lat);
          console.log(this.lat);
        }
      },
        (error: PositionError) => console.log(error));
    } else {
      alert("Geolocation is not supported by this browser.");
    }
  }
}

so im trying to get the location first and then call the getWeatherByCordinates method

getWeatherByCoordinates(){ 
    this.weatherService.getWeatherByLatAndLong(this.latitude,this.longitude).subscribe((res) =>{
      console.log('res',res);
    });
  }

in the ngOninit like so

ngOnInit() {
    this.getLocation();
    this.getWeatherByCoordinates();
}

CodePudding user response:

getLocation() {
    return new Promise((resolve, reject) => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position: Position) => {
          if (position) {
            console.log("Latitude: "   position.coords.latitude  
              "Longitude: "   position.coords.longitude);
            this.lat = position.coords.latitude;
            this.lng = position.coords.longitude;
            console.log(this.lat);
            console.log(this.lat);
            resolve({
              lat:position.coords.latitude,
              lng:position.coords.longitude
            })
          }
        },
          (error: PositionError) => reject(error));
      } else {
        alert("Geolocation is not supported by this browser.");
      }
    });
  }



async ngOnInit() {
    await this.getLocation();
    this.getWeatherByCoordinates();
}

Or Can use callback for this case

getLocation(callback) {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position: Position) => {
        if (position) {
          console.log("Latitude: "   position.coords.latitude  
            "Longitude: "   position.coords.longitude);
          this.lat = position.coords.latitude;
          this.lng = position.coords.longitude;
          console.log(this.lat);
          console.log(this.lat);
          callback()
        }
      },
        (error: PositionError) => console.log(error));
    } else {
      alert("Geolocation is not supported by this browser.");
    }
  }
}

ngOnInit() {
        this.getLocation(this.getWeatherByCoordinates());
}
  • Related