Back to Homepage
Tuesday 13 August 2024
7

What is a promise in javascript?

In JavaScript, a promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a cleaner, more intuitive way to handle asynchronous code compared to traditional callback functions, helping to avoid issues like "callback hell."

Understanding Promises

A promise in JavaScript can be in one of three states:

1. Pending: The initial state, where the operation has not yet completed.

2. Fulfilled: The operation completed successfully, and the promise has a resulting value.

3. Rejected: The operation failed, and the promise has a reason for the failure.

When a promise is fulfilled or rejected, it is said to be "settled," meaning it will not change state again.

Creating a Promise

You can create a new promise using the Promise constructor, which takes a function (known as the executor) with two arguments: resolve and reject.

1. Example of Creating a Promise:

const myPromise = new Promise((resolve, reject) => {
       const success = true;

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

Explanation:

  • If success is true, the promise is resolved with a message.
  • If success is false, the promise is rejected with an error message.

Handling Promises with .then() and .catch()

To handle the result of a promise, you use the .then() method for fulfilled promises and the .catch() method for rejected promises.

2. Handling a Fulfilled Promise:

myPromise.then((message) => {
       console.log(message); // Output: Operation was successful!
   });

Explanation:

  • The .then() method takes a function that runs when the promise is fulfilled.

3. Handling a Rejected Promise:

myPromise.catch((error) => {
       console.error(error); // Output: Operation failed.
   });

Explanation:

  • The .catch() method takes a function that runs when the promise is rejected.

Chaining Promises

Promises can be chained to handle multiple asynchronous operations in sequence. Each .then() method returns a new promise, allowing you to chain additional .then() or .catch() calls.

4. Example of Chaining Promises:

myPromise
       .then((message) => {
           console.log(message);
           return "Next operation";
       })
       .then((nextMessage) => {
           console.log(nextMessage); // Output: Next operation
       })
       .catch((error) => {
           console.error(error);
       });

Explanation:

  • The first .then() resolves with a message and passes it to the next .then() in the chain.
  • If any promise in the chain is rejected, the .catch() method handles the error.

Using Promise.all() for Concurrent Promises

The Promise.all() method allows you to run multiple promises concurrently and waits until all of them are settled. It returns a single promise that resolves with an array of results or rejects with the first encountered error.

5. Example of Promise.all():

const promise1 = Promise.resolve("First");
   const promise2 = Promise.resolve("Second");
   const promise3 = Promise.resolve("Third");

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

Explanation:

  • All promises in the array [promise1, promise2, promise3] are resolved, and the results are returned in the same order.

Practical Use Cases

  • Fetching data from an API: Promises are often used with fetch() to handle asynchronous HTTP requests.
  • Running multiple asynchronous tasks: Use Promise.all() or Promise.race() to manage concurrent tasks.
  • Handling user input: Promises can manage asynchronous validation or processing of user input.

Best Practices

  • Always handle errors using .catch() to avoid unhandled promise rejections.
  • Use chaining to manage complex asynchronous workflows in a readable manner.
  • Combine promises with Promise.all() or Promise.allSettled() to handle multiple asynchronous operations efficiently.

Official References

Promises in JavaScript provide a powerful way to handle asynchronous operations, making your code more readable and manageable. By mastering promises, you can write more robust and efficient JavaScript applications.

Share:
Created by:
Author photo

Jorge García

Fullstack developer