DEV Community

Cover image for Understanding JavaScript Promises
Vrushik Visavadiya
Vrushik Visavadiya

Posted on • Edited on

Understanding JavaScript Promises

Introduction

JavaScript Promises are a powerful feature that allows you to handle asynchronous operations more efficiently. In this blog post, we will explore what promises are, how they work, and provide examples to illustrate their usage.

What is a Promise?

A promise is an object representing the eventual completion or failure of an asynchronous operation. It can be in one of three states:

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

Creating a Promise

You can create a promise using the Promise constructor, which takes a function as an argument. This function is called the executor and it receives two arguments: resolve and reject.

const myPromise = new Promise((resolve, reject) => {
  // Asynchronous operation
  let success = true;

  if (success) {
    resolve("Operation was successful!");
  } else {
    reject("Operation failed!");
  }
});
Enter fullscreen mode Exit fullscreen mode

Using Promises

To handle the result of a promise, you use the .then() and .catch() methods.

myPromise
  .then((message) => {
    console.log(message); // Output: Operation was successful!
  })
  .catch((error) => {
    console.error(error); // This won't run in this example
  });
Enter fullscreen mode Exit fullscreen mode

Chaining Promises

Promises can be chained to handle a sequence of asynchronous operations.

const firstPromise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("First promise resolved!"), 1000);
});

firstPromise
  .then((message) => {
    console.log(message); // Output: First promise resolved!
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve("Second promise resolved!"), 1000);
    });
  })
  .then((message) => {
    console.log(message); // Output: Second promise resolved!
  })
  .catch((error) => {
    console.error(error);
  });

Enter fullscreen mode Exit fullscreen mode

Handling Multiple Promises

Promise.all and Promise.race are useful for handling multiple promises concurrently.

Promise.all

Promise.all waits for all promises to be fulfilled or any to be rejected.

const promise1 = new Promise((resolve) => setTimeout(resolve, 1000, 'First'));
const promise2 = new Promise((resolve) => setTimeout(resolve, 2000, 'Second'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 3000, 'Third'));

Promise.all([promise1, promise2, promise3])
  .then((values) => {
    console.log(values); // Output: ["First", "Second", "Third"]
  })
  .catch((error) => {
    console.error(error);
  });

Enter fullscreen mode Exit fullscreen mode

Promise.race

Promise.race returns the result of the first promise that settles (fulfills or rejects).

const promiseA = new Promise((resolve) => setTimeout(resolve, 1000, 'Fast'));
const promiseB = new Promise((resolve) => setTimeout(resolve, 2000, 'Slow'));

Promise.race([promiseA, promiseB])
  .then((value) => {
    console.log(value); // Output: "Fast"
  })
  .catch((error) => {
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

JavaScript Promises provide a robust way to manage asynchronous operations, avoiding the pitfalls of callback hell and making your code more readable and maintainable. Understanding and using promises effectively can significantly improve your JavaScript programming skills.


References

MDN Web Docs: Promises

Top comments (0)