Promises – JS

In JavaScript, a Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises are a powerful way to handle asynchronous operations in a more manageable and readable manner compared to traditional callback functions. Here’s an overview of Promises in JavaScript:

Basic Concepts

1. States of a Promise:

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: Operation completed successfully.
  • Rejected: Operation failed.

    2. Creating a Promise:

    let myPromise = new Promise((resolve, reject) => {
      // Asynchronous operation here
      let success = true; // Example condition
      if (success) {
        resolve("Operation was successful!");
      } else {
        reject("Operation failed.");
      }
    });

    3. Consuming a Promise:

    • then(): Invoked when the promise is fulfilled.

    • catch(): Invoked when the promise is rejected.

    • finally(): Invoked when the promise is settled (either fulfilled or rejected).

    myPromise
      .then((value) => {
        console.log(value); // "Operation was successful!"
      })
      .catch((error) => {
        console.error(error); // "Operation failed."
      })
      .finally(() => {
        console.log("Promise is settled.");
      });

    4. Chaining Promises:

      Promises can be chained to handle a sequence of asynchronous operations in a more readable manner.

      let promiseChain = new Promise((resolve, reject) => {
      resolve(1);
      });

      promiseChain
      .then((value) => {
      console.log(value); // 1
      return value * 2;
      })
      .then((value) => {
      console.log(value); // 2
      return value * 3;
      })
      .then((value) => {
      console.log(value); // 6
      })
      .catch((error) => {
      console.error(error);
      });

      Handling Multiple Promises

      1. Promise.all(): Waits for all promises to be fulfilled and returns an array of their results. If any promise is rejected, it returns the reason of the first promise that was rejected.

      let promise1 = Promise.resolve(3);
      let promise2 = 42;
      let promise3 = new Promise((resolve, reject) => {
        setTimeout(resolve, 100, 'foo');
      });
      
      Promise.all([promise1, promise2, promise3]).then((values) => {
        console.log(values); // [3, 42, "foo"]
      });

      2. Promise.race(): Returns the result of the first promise that settles (fulfills or rejects).

      let promise1 = new Promise((resolve, reject) => {
        setTimeout(resolve, 500, 'one');
      });
      
      let promise2 = new Promise((resolve, reject) => {
        setTimeout(resolve, 100, 'two');
      });
      
      Promise.race([promise1, promise2]).then((value) => {
        console.log(value); // "two"
      });

      3. Promise.allSettled(): Waits for all promises to settle (either fulfill or reject) and returns an array of objects describing the outcome of each promise.

      let promise1 = Promise.resolve(3);
      let promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
      let promise3 = 42;
      
      Promise.allSettled([promise1, promise2, promise3]).then((results) => results.forEach((result) => console.log(result.status)));
      // "fulfilled"
      // "rejected"
      // "fulfilled"

      4. Promise.any(): Returns the result of the first promise that fulfills. If all promises are rejected, it returns an AggregateError.

      let promise1 = Promise.reject(0);
      let promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'quick'));
      let promise3 = new Promise((resolve) => setTimeout(resolve, 500, 'slow'));
      
      Promise.any([promise1, promise2, promise3]).then((value) => {
        console.log(value); // "quick"
      }).catch((error) => {
        console.log(error);
      });

        Async/Await

        Async/await is syntactic sugar built on top of promises, making asynchronous code look and behave more like synchronous code.

        1. Async Functions: Declared with the async keyword.
        2. Await Expressions: Used to pause the execution of an async function until the promise settles.
        async function asyncFunction() {
        try {
        let result1 = await new Promise((resolve) => setTimeout(resolve, 100, 'first'));
        console.log(result1); // "first"
        let result2 = await new Promise((resolve) => setTimeout(resolve, 100, 'second'));
        console.log(result2); // "second"
        } catch (error) {
        console.error(error);
        }
        }

        asyncFunction();

        Error Handling

        Proper error handling in promises is crucial. Use .catch() in promise chains and try...catch blocks in async functions to manage errors.

        // Promise chain
        myPromise
        .then((value) => {
        throw new Error("Something went wrong!");
        })
        .catch((error) => {
        console.error(error); // "Something went wrong!"
        });

        // Async/await
        async function asyncFunction() {
        try {
        let result = await myPromise;
        } catch (error) {
        console.error(error); // Handle the error
        }
        }

        Understanding promises and using them effectively can greatly enhance your ability to handle asynchronous operations in JavaScript. They provide a cleaner and more maintainable way to manage asynchronous code compared to traditional callback patterns.

        Tags: No tags

        Add a Comment

        Your email address will not be published. Required fields are marked *