【问题标题】:return a value from $.get从 $.get 返回一个值
【发布时间】:2020-03-31 17:44:54
【问题描述】:

我需要构建一个返回访问者国家代码的函数,如下所示:

function getIsoCodeFromIp() {
    try {
        var response = await $.get("http://ip-api.com/json", null, "jsonp");
        return response.countryCode;
    } catch (error) {
        return null;
    }
}

我应该如何回复这个回复?

我有一个 JSON,我需要一个两个字母的字符串作为输出,不多不少,但是用这种异步方法来做这些简单的事情似乎很复杂。

我不需要将它记录到控制台,我需要返回它。

【问题讨论】:

    标签: javascript jquery asynchronous async-await


    【解决方案1】:

    您只能在async 函数中使用await

    // placed `async` before function
    async function getIsoCodeFromIp() {
        try {
            var response = await $.get("http://ip-api.com/json", null, "jsonp");
            return response.countryCode;
        } catch (error) {
            return null;
        }
    }
    
    // async function returns Promise, use then(callback)
    getIsoCodeFromIp().then(function(result){
        console.log(result); //here
    });
    

    现在它返回 Promise,因为它是异步函数。您需要通过then() 函数来捕捉响应。

    【讨论】:

    • 有没有办法返回,但是不是一个承诺,而是一个字符串?
    • 不使用异步函数,&.get 是异步的,所以你必须await。这就是 Promise 存在的原因。
    【解决方案2】:

    最后,这可以在这样的函数中恢复

    fetch('http://ip-api.com/json')
        .then((r) => r.json())
        .then((d) => console.log(d.countryCode));
    

    当然,问题是关于如何返回字符串,而不仅仅是记录答案。

    但是,如果我们找到一种方法来链接异步调用,这将是最好的答案和性能。现在,如果我们想要线程阻塞的同步返回......我从来没有找到关于这个问题的答案......可能每个人都会试图说服只保留第一个解决方案......

    例如。您可以链接调用以获得所需的结果。比如说,您需要从第一次调用的 ISO2 国家代码中获取一个 ISO3 国家代码。为了使用 ISO3 国家代码的第二个 API,您可能必须执行以下操作:

    fetch('http://ip-api.com/json')
            .then((j1)=>j1.json())                           // get iso2 country code
        .then((iso2)=>fetch('http://country.io/iso3.json')
            .then((j2)=>j2.json())                           // get iso3 code  
        .then((iso3)=>console.log(iso3[iso2.countryCode]))); // combine 1st result & 2nd
    

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2014-10-21
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多