Understanding JavaScript Promises

2 min | March 10, 2025

JavaScript Promises are a fundamental concept for handling asynchronous operations. They provide a cleaner way to work with asynchronous code compared to traditional callback functions.

What is a Promise?

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. It has three possible states:

  • Pending: Initial state, the operation hasn't completed yet.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Creating a Promise

You can create a Promise using the new Promise() constructor. It takes a function with two parameters: resolve (for success) and reject (for failure).

Example:

javascript
1const myPromise = new Promise((resolve, reject) => { 2 let success = true; 3 4 setTimeout(() => { 5 if (success) { 6 resolve("Operation successful"); 7 } else { 8 reject("Operation failed"); 9 } 10 }, 2000); 11}); 12 13myPromise 14 .then((message) => console.log(message)) // Runs if resolved 15 .catch((error) => console.log(error)); // Runs if rejected

Chaining Promises

Promises can be chained using .then() to handle sequential asynchronous operations.

Example:

javascript
1function fetchData() { 2 return new Promise((resolve) => { 3 setTimeout(() => resolve("Data fetched"), 1000); 4 }); 5} 6 7function processData(data) { 8 return new Promise((resolve) => { 9 setTimeout(() => resolve(`${data} -> Processed`), 1000); 10 }); 11} 12 13function saveData(data) { 14 return new Promise((resolve) => { 15 setTimeout(() => resolve(`${data} -> Saved`), 1000); 16 }); 17} 18 19fetchData() 20 .then((data) => processData(data)) 21 .then((processedData) => saveData(processedData)) 22 .then((finalData) => console.log(finalData)) 23 .catch((error) => console.log(error));

Handling Errors with .catch()

Errors in a promise chain can be caught using .catch(), which handles any rejection occurring in the chain.

javascript
1fetchData() 2 .then((data) => { 3 throw new Error("Something went wrong"); 4 }) 5 .catch((error) => console.log("Error handled:", error.message));

Using Promise.all() for Parallel Execution

Promise.all() allows multiple promises to execute in parallel and waits for all of them to resolve.

Example:

javascript
1const promise1 = new Promise((resolve) => 2 setTimeout(() => resolve("Task 1"), 1000) 3); 4const promise2 = new Promise((resolve) => 5 setTimeout(() => resolve("Task 2"), 2000) 6); 7const promise3 = new Promise((resolve) => 8 setTimeout(() => resolve("Task 3"), 1500) 9); 10 11Promise.all([promise1, promise2, promise3]) 12 .then((results) => console.log("All done:", results)) 13 .catch((error) => console.log(error));

Conclusion

JavaScript Promises provide a robust way to handle asynchronous operations efficiently. By using .then() for chaining, .catch() for error handling, and utilities like Promise.all(), you can write clean and maintainable asynchronous code.

Related Blog