我尝试使用带有 async 和 wait 的 fetch 来获取此公共(public) API,但 fetch 方法返回 [object Object]:
我用来获取 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}`;
}
}
API 返回的结构(如果动物是 pig ):
{"color": "pink", "sound": "roinc"}
我正在另一个文件中导入我的类并将其调用为:
const animals = new FetchAnimalApi();
console.log(animals.getAnimalInfo('pig'));
那么,我做错了什么?
编辑:
现在我的 console.log() 显示了我想要打印的内容,但是当我返回响应时,我仍然得到 [object Object]:
function getInfo() {
const animals = new FetchAnimalApi();
return animals.getAnimalInfo('pig').then(result => result);
}
在调试时,我意识到在 const request = wait fetch(
http://my_api_url.com/ ${animal})
行之后,[object Object] 立即打印在屏幕上已执行。
最佳答案
您无法调用 console.log(animals.getAnimalInfo('pig'));
这边走。 animals.getAnimalInfo
返回一个 promise 。要获得结果,您应该使用 then
回调:
const animals = new FetchAnimalApi();
animals
.getAnimalInfo('pig')
.then(result => console.log(result));
关于javascript - 将 fetch 与 async/await 一起使用会返回 [object Object],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46374208/