Ask any question about JavaScript here... and get an instant response.
Why does `fetch()` return a promise, and how can I handle JSON data received from an API response?
Asked on Nov 08, 2025
Answer
The `fetch()` function returns a promise because it performs an asynchronous operation to request resources over the network. To handle JSON data from an API response, you can chain `.then()` methods to process the response.
<!-- BEGIN COPY / PASTE -->
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The `fetch()` function initiates a network request and returns a promise that resolves to the response.
- The first `.then()` checks if the response is successful (status code 200-299) and then calls `response.json()` to parse the JSON data.
- The second `.then()` handles the parsed JSON data.
- The `.catch()` handles any errors that occur during the fetch operation or JSON parsing.
Recommended Links:
