const searchbtn = document.getElementById('Search-btn');
const cityinput = document.getElementById('city-input');
const apiKey = 'key';
let lon;
let lat;
function GeoGet() {
let GeoApiUrl = `http://api.openweathermap.org/geo/1.0/direct?q=${cityinput.value}&limit=1&appid=${apiKey}`
fetch(GeoApiUrl)
.then(response => response.json())
.then(data => {
lon = data[0].lon;
lat = data[0].lat;
console.log(lon)
console.log(lat)
})
.catch(error => {
console.error();
});
}
searchbtn.onclick = () => {
GeoGet();
console.log(lon);
console.log(lon);
}
I want to change the lon and lat in the function, but it does not work.
I can’t understand why
3
Answers
The problem is that you console log the variables before they were changed. This is because the code runs in sync and it does not wait for the response.
Try this:
The problem is that you are using a
fetch
call, which is aPromise
, but are not waiting for thethen
callback to be finished before executing theconsole.log
in youronclick
. You’ll either need to makeGetGet
anasync
function and call it viaawait
inonclick
(making thatasync
too), or place theconsole.log
s inside thethen
callback. The latter is preferable, asawait
calls are blocking.Blocking With
async
/await
Non-Blocking With Moving
console.log
sAs discussed in comment and some guys explained in other posts about
fetch
,So here’s solution using
async
&await
: