What is fetch()?
fetch() is used to request data from a server (GET, POST, etc.).
It returns a Promise that resolves to a Response object.
example:
let response = fetch("https://jsonplaceholder.typicode.com/posts");
console.log(response); // Promise { <pending> }
Why Promise with fetch()?
Because fetching data from a server takes time (network delay).
Promise allows JS to continue running other code until the response arrives.
Example with .then() handling:
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data)) // Handle the data
.catch(error => console.log("Error:", error));
Common Use Cases
- Fetching user data from APIs.
- Sending form data to a server.
- Handling errors (like 404 or network failure).
Top comments (0)