从$ .get返回一个值

时间:2020-03-30 22:36:52

标签: javascript jquery asynchronous async-await

我需要构建一个确实会向我返回访客国家代码的函数,如下所示:

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

我应该如何退回该答复?

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

我不需要将其登录到控制台,我需要返回

2 个答案:

答案 0 :(得分:3)

您只能在=QUERY( { IMPORTRANGE("url", "'Parte 1'!A1:AH"); IMPORTRANGE("url", "'Parte 2'!A1:AH"); IMPORTRANGE("url", "'Parte 3'!A1:AH"); IMPORTRANGE("url", "'Parte 4'!A1:AH") }, "Select Col2, Col1, Col34, Col24, Col3, Col4, Col5, Col6, Col11, Col7, Col8, Col9, Col10, Col12, Col13, Col14, Col15, Col20, Col21, Col22, Col23 Where Col10="&$C$1&" And Col22 != 'Duplicado'") 函数中使用await

async

现在它返回承诺,因为它是异步功能。您需要通过// 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 }); 函数来捕获响应。

答案 1 :(得分:0)

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

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

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

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

例如您可以链接呼叫以获得所需的结果。假设您需要从首次通话的ISO2国家代码中获取ISO3国家代码。为了将第二个API用于ISO3国家/地区代码,您必须执行以下操作:

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
相关问题