Variable losing value outside scope


#1

Hi, I need some advise from the forum experts.
I have a geolocation function inside the ionViewDidLoad scope, but it loses the value if I call the variable outside.

If I do console.log inside ionViewDidLoad it will print the correct value, but if I do it outside, it will show undefined.

PS: all variables are public.

ionViewDidLoad(){
  this.location.getCurrentPosition().then((resp) => {
    this.latitude = resp.coords.latitude;
    this.longitude = resp.coords.longitude;
    console.log(this.latitude)  <= this will print the latitude
  }
  console.log(this.latitude) <= this will print undefined
}

someFunction(){
  console.log(this.latitude) <= this will print undefined
}

#2

its because you are using promise that is asynchronous way to run code or in other words promises run asynchronously try calling somefunction inside then of promise you will get ur result


#3

Hi thanks for your answer, but can I ask you to give an example?


#4

@tokuhara Use the code bellow and see the logs:

ionViewDidLoad(){
	this.location.getCurrentPosition().then((resp) => {
		this.latitude = resp.coords.latitude;
		this.longitude = resp.coords.longitude;
		console.log('after getCurrentPosition (only now you have the data)');
		console.log('latitude-01', this.latitude);
		this.someFunction(); // here you will print the correct value
	});
	console.log('latitude-02', this.latitude);
	this.someFunction(); // here the promise won't have returned yet
}

someFunction(){
	console.log('someFunction', this.latitude);
}

Keep in mind that what is chained in the promise will execute asynchronously:

.then(resp => { /* here */ })

I advise to read about promises:



#5

Thanks, I will take a look!