提问者:小点点

如何在全局变量中为Node JS中的“然后”赋值以供以后使用[重复]


原始关闭原因未得到解决

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);

如何将值分配给全局变量,以便它可以在代码中的任何位置使用。当我尝试这个方法时,我从console.log得到了“未定义”作为我的解决方案。


共1个答案

匿名用户

我认为在调用函数 getCity() 时不需要等待。我无法获得值,但我修复了错误。试试这个:

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)
    }
);