This website requires JavaScript.
JavaScript Promises Cheatsheet

Javascript Promises - Specific functions and use cases

Do you know everything about Promises? What is the difference between them?

9 min read

I. Problem

Promises in JavaScript are a powerful way to handle asynchronous operations. They help create cleaner and more manageable code than traditional callbacks, especially when working with multiple asynchronous operations. However, they can also lead to complex and hard-to-read code if not used properly. In this article, we will explore some common problems with promises and how to solve them using modern JavaScript features.

II. Create a Promise

A Promise is an object that represents the result of an asynchronous operation. It can be in one of three states: pending, fulfilled, or rejected. To create a Promise, you use a constructor with an execution function that takes two parameters: resolve and reject.

const myPromise = new Promise((resolve, reject) => {
  let success = true; // change to false to activate reject
  setTimeout(() => {
    success ? resolve("Promise Resolved!") : reject("Promise Rejected!");
  }, 1000);
});

In this example, we create a Promise that simulates an operation that takes 1 second to complete. If the success variable is true, the Promise will resolve with a success message; otherwise, it will reject with an error message.

III. Handling a Promise

After creating a Promise, you need to handle its result, whether it succeeds or fails. JavaScript provides three main methods:

myPromise
  .then((result) => console.log(result))     // Handle success
  .catch((error) => console.error(error))    // Handle error
  .finally(() => console.log("Promise Completed")); // Always executed

The .then() method takes a callback function that will be called when the Promise resolves. .catch() catches an error if the Promise is rejected. .finally() executes code regardless of the result, often used to clean up resources.

IV. Chaining Promises

One of the biggest benefits of Promises is the ability to chain asynchronous operations, creating a clear workflow:

const chainedPromise = new Promise((resolve) => {
  setTimeout(() => resolve(10), 1000);
})
  .then((num) => num * 2)         // 10 * 2 = 20
  .then((num) => num + 5)         // 20 + 5 = 25
  .then((num) => console.log("Final Result:", num)); // Print 25

Each .then() returns a new Promise, allowing us to process the return value from the previous Promise and pass the result to the next Promise in the chain.

V. Promise.all - Execute Multiple Promises in Parallel

When you need to execute multiple asynchronous operations at the same time and wait for them all to complete, Promise.all is the solution:

Promise.all([
  Promise.resolve("Task 1"),
  Promise.resolve("Task 2"),
  Promise.reject("Task 3 Failed"),
])
  .then((values) => console.log("All resolved:", values))
  .catch((err) => console.error("One failed:", err));

Promise.all takes an array of Promises and returns a new Promise. This new Promise will resolve when all Promises in the array succeed, with an array of results in the corresponding order. If any Promise fails, Promise.all will reject immediately.

VI. Promise.allSettled - Waits for all Promises to complete

Unlike Promise.all, Promise.allSettled waits for all Promises to complete, regardless of success or failure:

Promise.allSettled([
Promise.resolve("Success 1"),
Promise.reject("Error 2"),
])
.then((results) => console.log("All Settled:", results));

The result is an array of objects, each object describing the state of each Promise (fulfilled or rejected) along with a value or error reason. This is a great way to handle multiple independent Promises without worrying about some failing.

VII. Promise.race - Get the fastest result

Promise.race returns the first Promise that completes (whether it succeeds or fails):

Promise.race([
  new Promise((res) => setTimeout(() => res("Fast"), 1000)),
  new Promise((res) => setTimeout(() => res("Slow"), 2000)),
])
  .then((winner) => console.log("Race Winner:", winner));

In this example, the first Promise will complete in 1 second, so Promise.race will resolve with a value of "Fast" without waiting for the second Promise. This is a great way to set timeouts for API requests.

VIII. Promise.any - Get the first successful result

Promise.any returns the first successful Promise and ignores failed Promises:

Promise.any([
  Promise.reject("Fail 1"),
  Promise.resolve("Success 2"),
  Promise.resolve("Success 3"),
])
  .then((firstSuccess) => console.log("First Fulfilled:", firstSuccess))
  .catch((error) => console.error("All Failed:", error));

In this example, even though the first Promise is rejected, Promise.any will resolve with "Success 2" - the first successful Promise. It only rejects if all Promises fail.

IX. Async/Await vs Try-Catch

Async/Await is a modern syntax that makes asynchronous code more readable, like synchronous code:

const asyncFunction = async () => {
  try {
    const response = await new Promise((resolve) =>
      setTimeout(() => resolve("Async/Await Success"), 1000)
    );
    console.log(response);
  } catch (error) {
    console.error("Error:", error);
  }
};

asyncFunction();

The async keyword declares an asynchronous function that returns a Promise. The await keyword pauses the execution of the function until the Promise is resolved. The try-catch construct catches errors if the Promise is rejected. This approach makes complex asynchronous logic easier to follow.

  • Tags:
  • javascript
May 14, 2025
Previous page
9 lines of JavaScript replace 50 lines of code
Next page
Event Loop in Nodejs

šŸƒ Related posts