Soy muy nuevo en JS y esta es mi primera publicación en Stack Overflow. Espero estar haciéndolo bien.
Actualmente estoy codificando un sitio que usa varias API. Me gustaría ingresar los datos recibidos a través de estas API en variables globales para poder reutilizarlos en mis otras funciones. Sin embargo, me he encontrado con varios temas hablando de un mismo problema, pero no he encontrado una solución para mi caso específico. Lo siento mucho si la respuesta ya está en este sitio, pero no la encontré.
Cuando coloco console.log para depurar mi código, mis variables globales se muestran con sus valores iniciales, como si no se hubieran modificado. Pero cuando entro en console.log en la consola de mi navegador, mis variables se muestran con el valor actualizado .
Aquí hay una parte de mi código que no funciona como esperaba:
/* 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 //... }Espero haber dado suficiente información sobre mi problema.