【发布时间】: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