Promises and Error Handling in JS
JavaScript uses Promises to handle asynchronous operations like fetching data from an API. There are two main ways to work with Promises:
- Using
.thenand.catch - Using
try...catchwithasync/await
1. .then() - Handling Promise Success
Section titled “1. .then() - Handling Promise Success”The .then() method is used to handle the successful result of a Promise.
Syntax:
promise.then(successCallback);promiseis the Promise you are working with.successCallbackis 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.
2. .catch() - Handling Errors in Promises
Section titled “2. .catch() - Handling Errors in Promises”The .catch() method is used to handle errors (if the Promise fails).
Syntax:
promise.catch(errorCallback);errorCallbackis 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?
- If the fetch request fails,
.catch(error => console.error(error))runs.
3. try...catch - Handling Errors in async/await
Section titled “3. try...catch - Handling Errors in async/await”The 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?
- The
tryblock runs the API call. - If any error occurs, the
catchblock handles it.
4. When to Use .then().catch() vs. try...catch?
Section titled “4. When to Use .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 |
- Use
.then().catch()for simple promise chains. - Use
try...catchwithasync/awaitfor better readability and error handling.
Example Comparison:
- Using
.then().catch()
fetch("https://jsonplaceholder.typicode.com/posts") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Error:", error));- Using
async/awaitwithtry...catch
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();