I'm trying to get a value from a fetch function, but it arrives later then I try to use it. How can I make all my further program wait until this value arrives?
let res = 'Invalid query';
function callback(result) {
res = result;
console.log('inside callback: ', res);
return res;
}
function getData(callback) {
return fetch('https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400')
.then(response => response.json())
.then(json => {
callback(json.results.sunrise);
})
.catch((error) => {
console.error(error);
});
}
getData(callback); // returns to console: inside callback: 5:46:40 AM -> which is what I need
console.log(res); // returns 'Invalid query', which is an initial value
If I use
setTimeout(function() { console.log(res); }, 2000);
it gives the right result, but I need all my further program to wait for this value either.