Understanding Promises in JavaScript: A Comprehensive Guide



This content originally appeared on DEV Community and was authored by Muhammad Atif Latif

In this post, we’ll explore Promises in JavaScript, a powerful feature for handling asynchronous operations. We’ll cover what Promises are, how to use them, and some common patterns.

What is a Promise?

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It can be in one of three states:

  • Pending: The initial state, neither fulfilled nor rejected.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Creating a Promise

You can create a Promise using the Promise constructor:

const myPromise = new Promise((resolve, reject) => {
    // Asynchronous operation
    const success = true; // Change this to false to see rejection

    if (success) {
        resolve('Operation was successful!');
    } else {
        reject('Operation failed.');
    }
});

Using Promises

You can handle the result of a Promise using .then() for fulfilled promises and .catch() for rejected promises:

myPromise
    .then(result => {
        console.log(result); // Output: Operation was successful!
    })
    .catch(error => {
        console.error(error); // Output: Operation failed.
    });

Chaining Promises

Promises can be chained to perform multiple asynchronous operations in sequence:

const firstPromise = new Promise((resolve) => {
    setTimeout(() => resolve('First operation complete'), 1000);
});

firstPromise
    .then(result => {
        console.log(result);
        return new Promise((resolve) => {
            setTimeout(() => resolve('Second operation complete'), 1000);
        });
    })
    .then(result => {
        console.log(result);
    });

Using Promise.all()

If you want to execute multiple promises in parallel and wait for all of them to complete, use Promise.all():

const promise1 = Promise.resolve('Promise 1 resolved');
const promise2 = Promise.resolve('Promise 2 resolved');

Promise.all([promise1, promise2])
    .then(results => {
        console.log(results); // Output: [ 'Promise 1 resolved', 'Promise 2 resolved' ]
    })
    .catch(error => {
        console.error('One of the promises failed:', error);
    });

Conclusion

Promises are a powerful way to handle asynchronous operations in JavaScript, making your code cleaner and easier to manage. Understanding how to create, use, and chain promises is essential for modern JavaScript development.

Feel free to share your thoughts or any questions in the comments below!


This content originally appeared on DEV Community and was authored by Muhammad Atif Latif