I'm trying to fetch this public API using fetch with async and await, but the fetch method is returning an [object Object]:
The class I'm using to fetch the API:
class FetchAnimalApi {
async getAnimalInfo(animal) {
const request = await fetch(`http://my_api_url.com/${animal}`);
const response = await request.json();
return `${animal} goes like ${response.sound}`;
}
}
The structure the API is returning (if the animal is a pig):
{"color": "pink", "sound": "roinc"}
I'm importing my class in another file and calling it as:
const animals = new FetchAnimalApi();
console.log(animals.getAnimalInfo('pig'));
So, what am I doing wrong?
EDIT:
Now my console.log() shows exactly what I want to print, but when I return the response, I'm still getting [object Object]:
function getInfo() {
const animals = new FetchAnimalApi();
return animals.getAnimalInfo('pig').then(result => result);
}
While debugging, I realized that [object Object] is being printed in my screen right after const request = await fetch(http://my_api_url.com/${animal}) line is executed.
[object Object]is probably just because of a string conversion in your final output. If youconsole.log()the output directly, you should see the desired object. You can't put an object into a template literal and get the properties printed out. Also,getAnimailInfo()returns a promise. So, you have to either useawaitwith it or.then()to get the value from that promise.[object Object], i.e. not a list of properties.[object Object]. See the console output for this: jsfiddle.net/me0g20cx. You could override.toString()on your object and provide a custom string conversion if you wanted, but template literals don't do that on their own.