javascript - 将 fetch 与 async/await 一起使用会返回 [object Object]

标签 javascript asynchronous ecmascript-6 promise

我尝试使用带有 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/

相关文章:

javascript - 为什么 Javascript RegExp 有一个双对象原型(prototype)

javascript - Materialise closeModal 未触发完成

javascript - eslint 脚本因meteor run npm eslint 失败

javascript - 为什么我们需要 Function.prototype.call ,我们可以通过将函数附加到 JavaScript 中的对象来实现相同的效果

javascript - 切换表格 <tr> 的显示 :none using Javascript

javascript - 如何向动态创建的元素添加点击功能?

spring - 使用 Kotlin 的异步 Spring Boot 不起作用

kotlin - 为什么协程作用域启动由不同的线程运行?

javascript - ES2015+ 有效地将对象数组转换为以对象数组作为值的分组 HashMap 的方法

javascript - 如何在 Meteor 1.4.x 中运行为 NodeJS v6 LTS ES2015 编写的模块?