Sobes.tech
Junior

What types of Promise do you know?

sobes.tech AI

Answer from AI

Main types of promises in Node.js:

  • Basic Promise: Represents a container for future values or errors. Has three states: pending, fulfilled, rejected. Created using the new Promise() constructor.

    // Creating a basic promise
    const myPromise = new Promise((resolve, reject) => {
      // Asynchronous operation
      setTimeout(() => {
        const success = true;
        if (success) {
          resolve("Operation completed successfully");
        } else {
          reject("An error occurred");
        }
      }, 1000);
    });
    
  • Promise.resolve(): Creates a promise that immediately transitions to the fulfilled state with a specified value.

    // Creating a resolved promise
    const resolvedPromise = Promise.resolve("This is an already fulfilled promise");
    
  • Promise.reject(): Creates a promise that immediately transitions to the rejected state with a specified reason.

    // Creating a rejected promise
    const rejectedPromise = Promise.reject(new Error("This is a rejected promise"));
    
  • Promise.all(): Accepts an array of promises and returns a new promise. This new promise transitions to fulfilled when all promises in the array are successfully completed. The value will be an array of results in the same order as the input promises. If any promise in the array is rejected, Promise.all() immediately rejects with the reason of the first rejected promise.

    // Using Promise.all()
    const promise1 = Promise.resolve(1);
    const promise2 = Promise.resolve(2);
    const promise3 = new Promise((resolve, reject) => setTimeout(() => resolve(3), 100));
    Promise.all([promise1, promise2, promise3])
      .then((values) => {
        // values will be [1, 2, 3]
      })
      .catch((error) => {
        // Error handling
      });
    
  • Promise.allSettled(): Accepts an array of promises and returns a new promise. This new promise transitions to fulfilled when all promises are either successfully completed (fulfilled) or rejected (rejected). The value will be an array of objects describing the result of each promise (status and value/reason). Unlike Promise.all(), it does not reject immediately.

    // Using Promise.allSettled()
    const promiseA = Promise.resolve("success");
    const promiseB = Promise.reject("error");
    Promise.allSettled([promiseA, promiseB])
      .then((results) => {
        // results will be an array of objects:
        // [{status: 'fulfilled', value: 'success'}, {status: 'rejected', reason: 'error'}]
      });
    
  • Promise.race(): Accepts an array of promises and returns a new promise. This new promise transitions to fulfilled or rejected with the result/reason of the first promise in the array that either successfully completes or rejects.

    // Using Promise.race()
    const promiseFast = new Promise((resolve, reject) => setTimeout(() => resolve("I am fast!"), 50));
    const promiseSlow = new Promise((resolve, reject) => setTimeout(() => resolve("I am slow..."), 500));
    Promise.race([promiseFast, promiseSlow])
      .then((value) => {
        // value will be "I am fast!"
      });
    
  • Promise.any(): Accepts an array of promises and returns a new promise. This new promise transitions to fulfilled with the value of the first promise that successfully completes. If all promises are rejected, Promise.any() rejects with an AggregateError containing all rejection reasons. Available starting from Node.js 12.

    // Using Promise.any()
    const promiseFail1 = Promise.reject("Error 1");
    const promiseSuccess = Promise.resolve("Success!");
    const promiseFail2 = Promise.reject("Error 2");
    Promise.any([promiseFail1, promiseSuccess, promiseFail2])
      .then((value) => {
        // value will be "Success!"
      })
      .catch((error) => {
        // Handling AggregateError if all promises are rejected
      });
    
What types of Promise do you know? — Node.js - sobes.tech