0
let city;
let c;

async function getCity() {
  let apiKey = '9ddf7197ff9633535259c99aa0716c329981d1514f05e2e1e2015803';
  let response = await fetch(`https://api.ipdata.co?api-key=${apiKey}`);
  let data = await response.json();
  city = data.city;
  return city;
}

getCity().then(
    function (value) {
        c = value.city;
    },
    function (error) {
        console.log(error)
    }
);

console.log(c);

How do I assign a value to a global variable so that it can be use anywhere in the code. As I tried this method but I am getting "undefined" as my solution from console.log.

  • You can use window, window is a global object in the browser but you shouldn't use global variables at all – kevinSpaceyIsKeyserSöze Nov 07 '22 at 15:01
  • You're assigning the value just fine to a global variable. The problem is that you attempt to use it immediately, not "later". This is why assigning variables asynchronously is a bad idea - you never know when they will have been assigned. – Bergi Nov 07 '22 at 15:49

1 Answers1

-1

I don't think you need to await when calling the function getCity(). I wasn't able to get a value, but I fixed the error. Try this:

let city;

async function getCity() {
  let apiKey = 'api_key';
  let response = await fetch(`https://api.ipdata.co?api-key=${apiKey}`);
  let data = await response.json();
  city = data.city;
  return city;
}

getCity().then(
    function (value) {
        console.log(value)
    },
    function (error) {
        console.log(error)
    }
);
ajdejesus
  • 74
  • 1
  • 6