-4

I have below code, I declared valuables globally in the file, and then I assigned value to the variable with in function. but when I tried to read the variable outside the function it gave undefined.

let latitude, longitude, IPLocation;
start(path)
console.log(IPLocation) // not work

async function start(path) {
IPLocation = await getData(path);
latitude = IPLocation.location.lat;
longitude = IPLocation.location.lng;
console.log(IPLocation) // work fine
}

async function getData(path) {
const data = await fetch(path);
const scrampled = await data.json();
parsed = await JSON.parse(JSON.stringify(scrampled));
return parsed
}

why that happen?

  • it has nothing to do with returning, he's changing the global variable inside the function but he does not await for that function to return before his `console.log` call – Cristian-Florin Calina Jul 11 '22 at 20:49
  • 2
    Why are you parsing the JSON and then immediately stringifying it and then parsing it again? – Andy Jul 11 '22 at 20:50

1 Answers1

0

It does not work because the function is async and you do not await for it.

let latitude, longitude, IPLocation;
await start(path)
console.log(IPLocation) // should work now

async function start(path) {
  IPLocation = await getData(path);
  latitude = IPLocation.location.lat;
  longitude = IPLocation.location.lng;
  console.log(IPLocation) // work fine
}

async function getData(path) {
  const data = await fetch(path);
  const scrampled = await data.json();
  parsed = await JSON.parse(JSON.stringify(scrampled));

  return parsed
}

OR if you are not in a module script (so you can't have top level await, use .then).

let latitude, longitude, IPLocation;
start(path).then(() => {
  console.log(IPLocation) // should work now
})