0

I am very new to JS and this is my very first post on Stack Overflow. I hope I'm doing it right.

I am currently coding a site that uses several APIs. I would like to enter the data received via these APIs into global variables so that I can reuse it in my other functions. However, I've come across several topics talking about the same issue, but I haven't found a solution for my specific case. I am very sorry if the answer is already on this site but I did not find it.

When I place console.log to debug my code, my global variables are displayed with their initial values, as if they had not been modified. But when I enter console.log myself in my browser's console, my variables are displayed with the updated value.

Here is a part of my code that does not work as I expected:

/* Here I initialise my global variables */
let cityName=" ", countryName=" ";
let lat=0, long=0;

function onload(){ //function called with body onload attribute
    getCurrentLocation();
    getTheWeatherChannel();
}

function getCurrentLocation(){
    /* API Call for IP based Location */
    $.post("https://ipapi.co/json", getLocation);

    function getLocation(data){
        cityName=data.city;
        countryName=data.country;
        lat=data.latitude;
        long=data.longitude;
        console.log(lat) //it returns the good latitude
    }
    console.log(lat) //still working
}

console.log(lat) //it returns 0 while I expected it to return the new latitude

function getTheWeatherChannel(){
    console.log(lat) //it returns 0...

    /* API Call for Weather */
    const key="*****";
    const urlCurrentInfo="https://api.weather.com/v1/geocode/"+lat+"/"+long+"/observations.json?language=en-US&units=m&apiKey="+key;
    //Here it stops working because API returns error with zero coordinates
    //...
}

I hope I have given enough information about my issue

Eseltwift
  • 1
  • 1
  • Your `console.log()` is executing before the return value from the POST. You must wait for the asynchronous code to finish before working with its results. – Scott Marcus Jun 03 '22 at 20:41
  • Welcome to asynchronous programming in JavaScript. Your `$.post()` callback will run when the HTTP request completes, but `$.post()` will return **immediately**. – Pointy Jun 03 '22 at 20:42
  • *"//it returns 0 while I expected it to return the new latitude"* - Why would you expect that? The code above that line defines variables, defines functions, and then outputs a variable. Nothing has *invoked* any of those functions yet. They've only been *defined*. – David Jun 03 '22 at 20:43
  • @David I forgot to say that my HTML body is written like that ``. I'll add it on my post – Eseltwift Jun 03 '22 at 20:49

0 Answers0