javascript - 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
解决方案
在 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){..} 的参数,它会立即调用此函数。
推荐阅读
- python - 如何在 python 的矩阵中交换列表?
- reporting-services - Reporting Services KPI 的自定义颜色
- regex - 批处理窗口中的正则表达式
- javascript - Facebook SDK FB.GetLoginStatus 加载被 X-Frame-Options 拒绝(仅限 Firefox)
- cakephp - 如何在 cakephp3.6 中返回带有原始 html 数据的电子邮件模板?
- python - 在 colab 中使用 keras_to_tpu_model 时,TPU 运行速度与 CPU 一样慢
- c# - 如何正确使用旧的 asp 站点 url 重定向到 MVC 路由?
- image - 电脑上的顶部页眉图像以及手机和平板电脑上的中心
- c++ - 用鼠标单击 OpenGL 拖动 3d 对象
- excel - .Formula 运行时错误 1004 在某些机器上而不是其他机器上