Reputation: 39
I'm using an api to get the capital of a country:
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)
}
}
It's working fine as long as I do this (it logs the capital and the little message):
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()
However, I tried to use an IIFE, which throws me an error message:
(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
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//finally%20%20%20%20%20%20%20%20console.log(%22finished%20operation%20getting%20city!%22)%7D net::ERR_ABORTED 404
Upvotes: 1
Views: 599
Reputation: 124
add a semicolon at the last line of whereAmI function. if you don't have the semicolon and directly add the IIFE block right after it, it would think your IIFE is an argument of your first 'whereAmI' function.
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!");
})()
without the semicolon, JS will interpret is as this:
const whereAmI = async function(country){
.....
}(async function(){...})()
where 'async function(){...}' can be interpreted as an argument of function(country){..} and it immediately invokes this function.
Upvotes: 2