I am trying to fetch some information from the given URL. I assigned the URL to a const named URL. I used the fetch api to take the info from the source as JSON format. I can't control the coming information.Here is my code;
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
I only need the
{
name: "...",
numberOfPages: "....",
released: "......",
},
{
name: "...",
numberOfPages: "....",
released: "......",
},
....
Return the values that you need from the api response. Here is the how you can do it:
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()))();
Result set from browser console:
Also, while waiting for promise to get fulfilled, you can do .then() or use await.
They both solve the same purpose.