1/1/1970
JavaScript uses Promises to handle asynchronous operations like fetching data from an API. There are two main ways to work with Promises:
.then and .catchtry...catch with async/await.then() - Handling Promise SuccessThe .then() method is used to handle the successful result of a Promise.
Syntax:
promise.then(successCallback);promise is the Promise you are working with.successCallback is the function that runs when the Promise is fulfilled.Example:
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data)); // Runs on successful fetchHow it works?
fetch() returns a Promise..then(response => response.json()) waits for the response and converts it to JSON..then(data => console.log(data)) runs after JSON conversion and logs the data..catch() - Handling Errors in PromisesThe .catch() method is used to handle errors (if the Promise fails).
Syntax:
promise.catch(errorCallback);errorCallback is the function that runs if the Promise is rejected.Example:
fetch("https://jsonplaceholder.typicode.com/invalid-url")
.then(response => response.json())
.catch(error => console.error("Error:", error)); // Handles errorHow it works?
.catch(error => console.error(error)) runs.try...catch - Handling Errors in async/awaitThe try...catch block is used to handle errors in synchronous and asynchronous code.
Syntax:
try {
// Code that may throw an error
} catch (error) {
// Handle the error
}Example with async/await:
async function fetchData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
fetchData();How it works?
try block runs the API call.catch block handles it..then().catch() vs. try...catch?| Feature | .then().catch() |
try...catch (with async/await) |
|---|---|---|
| Readability | Harder to read when chaining multiple .then() |
Easier to read and write |
| Error Handling | Errors caught in .catch() |
Errors handled inside catch {} |
| Use Case | Good for simple Promises | Better for async/await and complex logic |
.then().catch() for simple promise chains.try...catch with async/await for better readability and error handling.Example Comparison:
.then().catch()fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));async/await with try...catchasync function fetchData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
fetchData();