#atom
Content:
Promises in JavaScript are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They provide a cleaner and more structured way to handle asynchronous tasks compared to callbacks, avoiding issues like "callback hell." Promises are widely used in modern JavaScript for tasks like API calls, file I/O, and timers.

Key Concepts:

  1. What is a Promise?

    • A Promise is an object that can be in one of three states:
      • Pending: The initial state; the operation is still in progress.
      • Fulfilled: The operation completed successfully.
      • Rejected: The operation failed.
    • Once a Promise is fulfilled or rejected, it is considered "settled" and cannot change its state.
  2. Creating a Promise:

    • A Promise is created using the Promise constructor, which takes a function (called the executor) with two arguments: resolve and reject.
    • Example:
      const myPromise = new Promise((resolve, reject) => {
        setTimeout(() => {
          const success = true;
          if (success) {
            resolve("Operation succeeded!");
          } else {
            reject("Operation failed!");
          }
        }, 1000);
      });
      
  3. Consuming a Promise:

    • Promises are consumed using .then() for fulfillment, .catch() for rejection, and .finally() for cleanup.
    • Example:
      myPromise
        .then((result) => {
          console.log(result); // "Operation succeeded!"
        })
        .catch((error) => {
          console.error(error); // "Operation failed!"
        })
        .finally(() => {
          console.log("Promise settled.");
        });
      
  4. Chaining Promises:

    • Promises can be chained to perform sequential asynchronous operations.
    • Example:
      fetchData()
        .then((data) => processData(data))
        .then((processedData) => saveData(processedData))
        .catch((error) => console.error(error));
      

Promise Static Methods:

  1. Promise.all():

    • Takes an array of Promises and returns a single Promise that resolves when all input Promises have resolved, or rejects if any input Promise rejects.
    • Example:
      const promise1 = Promise.resolve(1);
      const promise2 = Promise.resolve(2);
      Promise.all([promise1, promise2])
        .then((results) => {
          console.log(results); // [1, 2]
        })
        .catch((error) => {
          console.error(error);
        });
      
  2. Promise.race():

    • Returns a Promise that resolves or rejects as soon as one of the input Promises resolves or rejects.
    • Example:
      const promise1 = new Promise((resolve) => setTimeout(resolve, 500, "First"));
      const promise2 = new Promise((resolve) => setTimeout(resolve, 1000, "Second"));
      Promise.race([promise1, promise2])
        .then((result) => {
          console.log(result); // "First"
        });
      
  3. Promise.allSettled():

    • Returns a Promise that resolves after all input Promises have settled (either fulfilled or rejected), providing an array of results.
    • Example:
      const promise1 = Promise.resolve(1);
      const promise2 = Promise.reject("Error");
      Promise.allSettled([promise1, promise2])
        .then((results) => {
          console.log(results);
          // [
          //   { status: "fulfilled", value: 1 },
          //   { status: "rejected", reason: "Error" }
          // ]
        });
      
  4. Promise.any():

    • Returns a Promise that resolves as soon as one of the input Promises fulfills. If all Promises reject, it rejects with an AggregateError.
    • Example:
      const promise1 = Promise.reject("Error 1");
      const promise2 = Promise.resolve("Success");
      Promise.any([promise1, promise2])
        .then((result) => {
          console.log(result); // "Success"
        });
      
  5. Promise.resolve():

    • Creates a Promise that is already resolved with a given value.
    • Example:
      const resolvedPromise = Promise.resolve("Resolved!");
      resolvedPromise.then((result) => console.log(result)); // "Resolved!"
      
  6. Promise.reject():

    • Creates a Promise that is already rejected with a given reason.
    • Example:
      const rejectedPromise = Promise.reject("Rejected!");
      rejectedPromise.catch((error) => console.error(error)); // "Rejected!"
      

Promise Prototype Methods:

  1. .then():

    • Attaches fulfillment and rejection handlers to the Promise.
    • Signature: then(onFulfilled?: (value: T) => TResult, onRejected?: (reason: any) => TResult): Promise<TResult>;
  2. .catch():

    • Attaches a rejection handler to the Promise.
    • Signature: catch(onRejected?: (reason: any) => TResult): Promise<TResult>;
  3. .finally():

    • Attaches a handler that runs when the Promise is settled, regardless of its outcome.
    • Signature: finally(onFinally?: () => void): Promise<T>;

Example: Combining Promises

const fetchUser = () => Promise.resolve({ id: 1, name: "Alice" });
const fetchPosts = () => Promise.resolve(["Post 1", "Post 2"]);

Promise.all([fetchUser(), fetchPosts()])
  .then(([user, posts]) => {
    console.log("User:", user);
    console.log("Posts:", posts);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

Linked Cards:

Tags: #JavaScript #Promises #AsynchronousProgramming #PromiseAll #ErrorHandling #AsyncAwait

Connections:


Sources: