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

Posted

技术标签:

【中文标题】JS:变量返回未定义,除了之前定义它【英文标题】:JS: Variable returning undefined except defining it earlier 【发布时间】:2020-07-25 10:57:36 【问题描述】:

我的代码是

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。我觉得它与异步和等待有关,但我不确定。

【问题讨论】:

如果您使用的是 async/await,那么您的 geoloc 函数应声明为 async function geoloc() @lawrence-witt 很抱歉造成混乱。我不确定如何应用 async / await 或是否应该应用。 【参考方案1】:

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>

【讨论】:

jsfiddle.net/Lyjkzqcf 没有错误,你需要使函数异步@MilkyDeveloper 嗯。它可以在我宝贵的本地主机服务器和 repl / jsfiddle 中运行。谢谢!很惊讶 SO 用户的反应如此之快。【参考方案2】:

试试

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 一次。

【讨论】:

以上是关于JS:变量返回未定义,除了之前定义它的主要内容,如果未能解决你的问题,请参考以下文章

axios.post 未从服务器返回数据:“无法解构‘(中间值)’的属性‘数据’,因为它未定义”

从 Vue CLI(Vue 3)迁移到 Vite:未捕获(承诺中)类型错误:无法解构“未定义”的属性“默认”,因为它未定义

无法读取属性历史记录,因为它未定义,但它是

TypeError:无法解构“对象(...)(...)”的属性“setValues”,因为它未定义。 (反应/创建反应应用)

反应使用上下文。无法解构“对象(...)(...)”的属性“currentChatbotInEdit”,因为它未定义。我该如何解决?

js 判断变量是否为空或未定义