Member-only story
JavaScript: How to get data returned from fetch?
1 min readJun 29, 2024
JavaScript has its own built-in way to make API requests. This is the Fetch API, a new standard to make server requests with Promises, but which also includes additional features.
The fetch() method returns a promise. After the fetch() method, include the Promise method then().
fetch(url).then(function() {
//handle the response
});
If the Promise returned is resolve, the function within the then() method is executed. That function contains the code for handling the data received from the API. After the then() method, include the catch() method.
fetch(url)
.then(function(){
//handle the response
})
.catch(function(){
//handle the error
});
Example retrieving data from an API
const url = "https://jsonmock.hackerrank.com/api/asteroids/search?parameter=&page=1";
function getData() {
return fetch(url)
.then((response) => {
return response.json()
.then((data) => {
console.log(data);
return data;
}).catch((err) => {
console.log(err);
})
});
}
function getActivity() {
let jsonData;
getData().then((data) => {
jsonData = data;
})
}
getActivity();