DEV Community

Cover image for Understanding JavaScript Promise Methods: A Simple Guide
Md Hamim
Md Hamim

Posted on • Originally published at seracoder.com

Understanding JavaScript Promise Methods: A Simple Guide

JavaScript, the backbone of modern web development, empowers developers to create dynamic and interactive web applications. One key feature that enhances the efficiency of handling asynchronous operations in JavaScript is Promises. In this article, we’ll take a closer look at JavaScript Promise methods in a straightforward manner.

Table of Contents

  • What are Promises?
  • How Promises Work
  • Promise Methods
    • 1. Promise.all()
    • 2. Promise.resolve()
    • 3. Promise.reject()
    • 4. Promise.race()
    • 5. More
  • Conclusion

What are Promises?

JavaScript Promise Actions

JavaScript Promise Actions

Before diving into Promise methods, let’s grasp the basic concept of Promises. A Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. It allows us to handle asynchronous code more elegantly and avoid the callback hell.

How Promises Work

  • Creation: To create a Promise, we use the Promise constructor. It takes a function as an argument, commonly referred to as the “executor.” This function receives two parameters: resolve and reject.

    const myPromise = new Promise((resolve, reject) => {
        // Simulating an asynchronous operation
        setTimeout(() => { 
          const operationSuccessful = true; // Set to true for success, false for failure
          if (operationSuccessful) {
            resolve('Operation completed successfully!');
          } else {
            reject('Operation failed!');
          }
        }, 1000); // Simulating a 1-second delay, replace with your actual asynchronous operation
      });
    
  • States: Promises have three states:

    • Pending: The initial state, representing that the asynchronous operation is still in progress.
    • Fulfilled: The state indicating that the operation completed successfully, and the promise now has a resulting value.
    • Rejected: The state indicating that the operation failed, and an error or reason for failure is provided.
  • Consuming Promises: We use .then() to handle the case when a Promise is fulfilled and .catch() for the case when it is rejected.

    myPromise
      .then((result) => {
        console.log('Success:', result);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
    
    

Promise Methods

1. Promise.all()

Promise.all() is used when you have multiple promises and want to wait for all of them to fulfill. If any promise in the array is rejected, the entire Promise.all() is rejected.

Parameters: An iterable of promises.

Return Value: A promise that resolves to an array of the fulfilled values of the input promises, in the same order.

const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);

Promise.all([promise1, promise2, promise3])
  .then(values => {
    console.log(values); // [1, 2, 3]
  })
  .catch(error => {
    console.error(error);
  });

Enter fullscreen mode Exit fullscreen mode

2. Promise.resolve()

This method returns a Promise object that is resolved with a given value. It is useful when you want to create a Promise that is already resolved with a specific value.

Parameters: A value to fulfill the promise with.

Return Value: A promise that is resolved with the given value.

const resolvedPromise = Promise.resolve('Resolved value');

resolvedPromise
  .then(value => {
    console.log(value); // 'Resolved value'
  });
Enter fullscreen mode Exit fullscreen mode

3. Promise.reject()

Contrary to Promise.resolve(), this method returns a Promise object that is rejected with a given reason (usually an error). It is handy when you need to create a Promise that is already rejected.

Parameters: A reason for the rejection.

Return Value: A rejected promise with the specified reason.

const reason = new Error('Custom rejection reason');
const rejectedPromise = Promise.reject(reason);

rejectedPromise
  .catch(error => {
    console.error(error); // 'Custom rejection reason'
  });
Enter fullscreen mode Exit fullscreen mode

4. Promise.race()

If you have multiple Promises and only need the result of the first one to resolve or reject, you can use Promise.race(). It returns a Promise that resolves or rejects as soon as one of the input Promises resolves or rejects.

Return Value: A promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.

Description: Promise.race() is useful when you are interested in the first settled promise, whether it’s fulfilled or rejected.

const promisesArray = [promise1, promise2, promise3];
Promise.race(promisesArray)
  .then((result) => {
    console.log('The first promise that resolves:', result);
  })
  .catch((error) => {
    console.error('The first promise that rejects:', error);
  });
Enter fullscreen mode Exit fullscreen mode

5. More

The methods I explained above are the ones you will like use most of the times. But there are several methods more that you might want to learn about.

All of these methods are explained in more detail on the MDN Web Docs. You can check that our as well to know how to uses them.

Conclusion

JavaScript Promise methods provide a clean and effective way to handle asynchronous operations. By understanding these simple methods, you can enhance your ability to manage asynchronous code, making your JavaScript applications more robust and responsive. As you explore these methods further, you’ll find them invaluable in simplifying your code and improving its readability.

Top comments (0)