【问题标题】:Async JS error message: > Uncaught TypeError: (intermediate value)(...) is not a function (more below)Async JS 错误消息:> Uncaught TypeError: (intermediate value)(...) is not a function (更多见下文)
【发布时间】:2021-07-15 15:02:51
【问题描述】:

我正在使用一个api来获取一个国家的首都:

const whereAmI = async function(country){
    try{
    const response = await fetch(`https://restcountries.eu/rest/v2/name/${country}`);
    
    if (!response.ok) throw new Error(`country not found (${response.status})`);
    
    const data = await response.json()
    
    return data[0]
    
} catch(error) {
        console.error('something went wrong: ' + error)
      }
}

只要我这样做,它就可以正常工作(它会记录大写字母和小消息):

async function test() {
    try{
        const data = await whereAmI('hungary');
        console.log(data.capital)
    } catch (err){
        console.error('async ' + err)
      }
    //finally
        console.log("finished operation getting city!")
}

test()

但是,我尝试使用 IIFE,这会引发错误消息:

(async function() {
    try{
        const data = await whereAmI('hungary');
        console.log(data.capital)
    } catch (err){
        console.error('async ' + err)
      }
    //finally
        console.log("finished operation getting city!")
})();

Uncaught TypeError: (intermediate value)(...) is not a function
获取 https://restcountries.eu/rest/v2/name/async%20function()%20%7B%20%20%20%20try%7B%20%20%20%20%20%20%20%20const%20data%20=%20await%20whereAmI('hungary');%20%20%20%20%20%20%20%20console.log(data.capital)%20%20%20%20%7D%20catch%20(err)%7B%20%20%20%20%20%20%20%20console.error('async%20'%20+%20err)%20%20%20%20%20%20%7D%20%20%20%20//finally%20%20%20%20%20%20%20%20console.log(%22finished%20operation%20getting%20city!%22)%7D 净::ERR_ABORTED 404

【问题讨论】:

  • 为什么脚本是 URL 的一部分?你怎么运行这个?它真的应该工作。

标签: javascript api asynchronous error-handling async-await


【解决方案1】:

在 whereAmI 函数的最后一行添加分号。如果您没有分号并直接在其后添加 IIFE 块,它会认为您的 IIFE 是您的第一个 'whereAmI' 函数的参数。

 const whereAmI = async function(country){
    try{
    const response = await fetch(`https://restcountries.eu/rest/v2/name/${country}`);
    
    if (!response.ok) throw new Error(`country not found (${response.status})`);
    
    const data = await response.json()
    
    return data[0]
    
} catch(error) {
        console.error('something went wrong: ' + error)
      }
};

(async function() {
    try{
        const data = await whereAmI('hungary');
        console.log(data.capital)
    } catch (err){
        console.error('async ' + err);
    }
    //finally
    console.log("finished operation getting city!");
})()

没有分号,JS会这样解释:

 const whereAmI = async function(country){
      .....
 }(async function(){...})()

其中 'async function(){...}' 可以解释为 function(country){..} 的参数,它会立即调用此函数。

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 2021-08-13
    • 2023-01-16
    • 2019-07-28
    • 2018-07-17
    相关资源
    最近更新 更多