Promises

Promises represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They provide a cleaner alternative to callbacks for managing async code.

Illustration of promises
Illustration of promises

💡 Core Concept

A Promise is an object that may be pending, fulfilled, or rejected. You attach handlers to handle success or failure once the async operation completes.

Creating a Promise

A Promise is created with a function that receives two callbacks: resolve and reject. Call resolve when your async task succeeds, reject if it fails.

📌 Deep Dive: Basic Promise Creation

JAVASCRIPT
const myPromise = new Promise((resolve, reject) => {
  const success = true; // simulate a condition
  if (success) {
    resolve('Operation succeeded');
  } else {
    reject('Operation failed');
  }
});

Consuming Promises

Use .then() to handle success, and .catch() to handle errors.

📌 Deep Dive: Handling Promise Results

JAVASCRIPT
myPromise
  .then(result => {
    console.log(result); // "Operation succeeded"
  })
  .catch(error => {
    console.error(error);
  });
Output
Operation succeeded

Promise States

Promise States
StateDescription
PendingInitial state; neither fulfilled nor rejected.
FulfilledOperation completed successfully.
RejectedOperation failed.

Chaining Promises

Promises can be chained to perform sequential asynchronous operations.

📌 Deep Dive: Promise Chaining

JAVASCRIPT
new Promise((resolve) => resolve(2))
  .then(value => value * 3)
  .then(value => {
    console.log(value); // 6
  });
Output
6

⚠️ Important

Always provide a .catch() handler to catch possible rejections and avoid unhandled promise rejections.

Promise Utility Methods

  • Promise.resolve(value): Returns a Promise resolved with value.
  • Promise.reject(error): Returns a Promise rejected with error.
  • Promise.all(iterable): Waits for all Promises to fulfill or any to reject.
  • Promise.race(iterable): Resolves or rejects as soon as any Promise resolves or rejects.

📌 Deep Dive: Using Promise.all

JAVASCRIPT
Promise.all([
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.resolve(3)
]).then(results => {
  console.log(results); // [1, 2, 3]
});
Output
[1, 2, 3]

💡 Summary

  • Promises simplify async code handling.
  • Use new Promise to create promises.
  • Attach .then() and .catch() for success and error handling.
  • Chain promises for sequential async operations.
  • Utility methods help coordinate multiple promises.