JS:变量返回未定义除了之前定义它

JS: Variable returning undefined except defining it earlier

我的密码是

var api_url

$.getJSON("https://api.ipify.org/?format=json", function(e) {
    myIP = e.ip;
    //api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
});

//api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP

function geoloc() {
  api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
  console.log(api_url)
  const response = await fetch(api_url)
  const data = await response.json();
  console.log(data)
}

geoloc();

我用 python 3 的 http.server 启动了它,它打印了 "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=undefined" 并且如预期的那样获取失败了。仔细检查后,定义了变量 myIP。我觉得它与异步和等待有关,但我不确定。

https://jsfiddle.net/Lyjkzqcf/

您可以在$.getJSON()方法中调用geoloc()。请看下面:

 var api_url
    
    $.getJSON("https://api.ipify.org/?format=json", function(e) {
        myIP = e.ip;
        geoloc();
        //api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
    });
    
    //api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
    
    async function geoloc() {
      api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
      console.log(api_url)
      const response = await fetch(api_url)
      const data = await response.json();
      console.log(data)
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

尝试

async function geoloc() {
  api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
  console.log(api_url)
  const response = await fetch(api_url)
  const data = response.json();
  console.log(data)
}

仅将函数声明为 asyncawait 一次。