首页 > 解决方案 > Async JS 错误消息:> Uncaught TypeError: (intermediate value)(...) is not a function(更多下文)

问题描述

我正在使用 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!")
})();

未捕获的类型错误:(中间值)(...)不是函数
GET 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//最后%20%20%20%20%20%20%20%20console.log(%22finished% 20operation%20getting%20city!%22)%7D net::ERR_ABORTED 404

标签: javascriptapiasynchronouserror-handlingasync-await

解决方案


在 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){..} 的参数,它会立即调用此函数。


推荐阅读