【问题标题】:Using Fetch to Return GitHub User Data使用 Fetch 返回 GitHub 用户数据
【发布时间】:2019-01-01 06:37:21
【问题描述】:

请原谅我的无知,我对 JavaScript 还不是很了解。我正在尝试从 GitHub 获取公共用户数据并将其显示在我的个人投资组合中。目前我有以下代码:

 getData(url) {
  return fetch(url);
}
const userData = getData("https://api.github.com/users/userName");

userData
  .then((response) => response.json())
  .then((response) => console.log(response))
  .catch((error) =>
    console.log("There was an error fetching the data: " + error)
  );

  console.log(userData)

我得到的响应是带有用户数据的 JSON,但是当我 console.log(userData) 我得到Promise { <state>: "pending" } 作为响应。

另外,我可以看到初始响应中有一个 id,但是当我 console.log(userData.id) 时,我得到 undefined

我已经阅读了 GitHub API 文档并观看了一些关于 Promises 的视频,但我似乎无法让我的代码正常工作。

感谢您抽出宝贵时间查看此内容,非常感谢您提供任何帮助!

【问题讨论】:

  • userData 是一个承诺。你的数据应该是response
  • 这就像一个魅力!非常感谢...最后一个问题 - 我将如何将响应中的信息设置为可以在响应代码之外使用的变量?

标签: javascript async-await es6-promise github-api


【解决方案1】:

这是因为 userData 是一个承诺。如果您尝试使用 async/await(文档可在 here 获取),您将能够同步获取数据。

 const getData = async (url) => {
   try {
     const data = await fetch("https://api.github.com/users/:user_name");
     console.log(data.json());
     return data;
   } catch (e) {
     console.log("There was an error fetching the data: " + error)
   }
 }

【讨论】:

  • 感谢您的回复!这将返回:Response ​ bodyUsed: false ​ headers: Headers { } ​ ok: true ​ redirected: false ​ status: 200 ​ statusText: "OK" ​ type: "cors" ​ url: "https://api.github.com/users/js-goose" ​ <prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … } 但我没有得到任何用户数据……我错过了什么吗?
  • @JonathanSexton 上面的代码记录了Response。用户数据由resp.json()获取,将Response的body解析成更友好的纯JS对象
  • @NinoFiliu 非常感谢您的澄清 - 经过一些重构,我最终让代码正常工作。再次感谢您!
猜你喜欢
  • 2016-08-06
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
  • 2018-09-12
相关资源
最近更新 更多