fetch
is used to make network requests (e.g., to a web API), and since network operations can take time to complete, you don't want your entire JavaScript execution to stop and wait for the response. Instead, fetch
returns a promise, which allows you to handle the response once the request is complete without blocking the rest of your code.fetch
, you often don't know how long the request will take due to network latency, server processing time, or other factors. Instead of waiting and freezing the execution, fetch returns a promise that you can work with. You can then handle success and error cases when the data arrives or if the request fails.fetch('https://jsonplaceholder.typicode.com/users')
: sends a request to retrieve an array of users from the provided API..then(res => res.json())
: once the response is received, this step parses the response as JSON
using .json()
, which itself returns a promise..then(res => console.log(res))
: logs the parsed JSON
data (a list of users) to the console..catch(e => alert('error'))
: if any error occurs during the fetch request (e.g., network failure), it catches the error and shows an alert with the message 'error'.catch
.then
!res.ok
) condition checks if the HTTP response is not successful (i.e., status codes outside the range of 200–299). If it's not, we throw an error with the response status..catch()
block now handles both network errors and any errors we throw when the response status is not OK. It logs the error in the console and alerts the user with a custom error message.