0

I am fetching some data from an api, but I wish to use this data outside the fetch function but I am getting undefined. Below is my function for fetch

var result;
function reverseGeocoding(latitude, longitude) {
    fetch("api_url"+latitude+longitude).then(
        res => {
            res.json().then(
                data => {
                    result = data.features[0].place_name;
                }
            )
        }
    )
    return result;
}
console.log(result);

How do I call reverseGeocodingand store the results?

  • Your code is doing the right thing, but by the time you `console.log(result)`, the promise might not have been fulfilled yet. To check this, do a `setTimeout` and `console log(result)` only after 5 seconds and see if your result has been set. – Lupu Ștefan Alex Jul 20 '20 at 14:09
  • You can use async await to handle this. – harpreet cheema Jul 20 '20 at 14:10

0 Answers0