【问题标题】:Javascript Fetch API can't control the coming responseJavascript Fetch API 无法控制即将到来的响应
【发布时间】:2021-09-27 17:42:48
【问题描述】:

我正在尝试从给定的 URL 获取一些信息。我将 URL 分配给了一个名为 URL 的 const。我使用 fetch api 从源获取信息为 JSON 格式。我无法控制即将到来的信息。这是我的代码;

const fetch = require("cross-fetch");
const URL = "https://anapioficeandfire.com/api/books"


// Important: Don't change the function name
const getBooks = async () => {
  // Your code goes here
  
  
  const response = await fetch(`${URL}`)
    .then(res => res.json())
    .then(data => console.log(data));
  const books = await response.json();
  return books;
}

getBooks().then(books => console.log(books))

This is the response from the code that I wrote
我只需要
{
名称:“...”,
numberOfPages: "....",
发布:“......”,
},
{
名称:“...”,
numberOfPages: "....",
发布:“......”,
},
....

【问题讨论】:

  • 接收到的数据中的其他属性有什么问题?您确实还没有明确而具体地确定您的实际问题是什么
  • 您正在混合使用 await.then() 语法。这导致您两次调用.json()console.log。您的代码中应该只有一个。

标签: javascript async-await fetch


【解决方案1】:

从 api 响应中返回您需要的值。 以下是您的操作方法:

const url = "https://anapioficeandfire.com/api/books";

const callApi = async () => {
const resp = await fetch(url);
const finalRes = await resp.json();
return finalRes.map((res) => {
    return {
    name: res.name,
    numberOfPages: res.numberOfPages,
    released: res.released,
    };
});
};

(async () => console.log(await callApi()))();

来自浏览器控制台的结果集:

此外,在等待 promise 完成时,您可以执行 .then() 或使用 await。 它们都解决了相同的目的。

【讨论】:

  • 您的示例代码中没有解构?
  • 是的,我直接在地图函数中返回所需的详细信息。但是我会改变答案。感谢您指出。
猜你喜欢
  • 2016-04-17
  • 2019-10-03
  • 2021-06-05
  • 2021-09-10
  • 2021-05-14
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 2022-08-05
相关资源
最近更新 更多