[英]Using fetch with async/await returns [object Object]
I'm trying to fetch this public API using fetch with async and await, but the fetch method is returning an [object Object]: 我正在尝试使用async和await的fetch来获取此公共API,但是fetch方法返回了[object Object]:
The class I'm using to fetch the API: 我用来获取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): API返回的结构(如果动物是猪):
{"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]: 现在,我的console.log()确切显示了我要打印的内容,但是当我返回响应时,我仍然得到[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. 在调试时,我意识到在执行
const request = await fetch(
http://my_api_url.com/ $ {animal} )
行之后,[object Object]正在被打印在屏幕上。
You can't call console.log(animals.getAnimalInfo('pig'));
您不能调用
console.log(animals.getAnimalInfo('pig'));
this way. 这条路。
animals.getAnimalInfo
returns a promise. animals.getAnimalInfo
返回承诺。 To get result, you should use then
callback: 为了获得结果,您应该使用
then
回调:
const animals = new FetchAnimalApi();
animals
.getAnimalInfo('pig')
.then(result => console.log(result));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.