Home » What is Promise in js?

What is Promise in js?

What is Promise in js?

Introduction

Promises form one of the basic building blocks of asynchronous programming in JavaScript. They represent a value that might be available now, or later in the future, or never. This is a far better way of dealing with operations in an asynchronous manner than using traditional callback functions, which lead to callback hell. Promises lead to a situation where callbacks are nested within other callbacks, which makes code harder to read and maintain.

What is a Promise?

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It can be used to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

Basic Syntax

A Promise can be created using the Promise constructor:

let promise = new Promise((resolve, reject) => {
  // asynchronous operation here
  if (/* operation successful */) {
    resolve('Success');
  } else {
    reject('Failure');
  }
});
JavaScript

States of a Promise

A Promise can be in one of three states:

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

Handling Promises

Promises comes with a .then() method used for handling successful completion and a .catch() method for error handling. There’s also a method .finally() for running some code after the Promise is settled, regardless of its outcome.

promise
  .then(result => {
    console.log('Success:', result);
  })
  .catch(error => {
    console.log('Error:', error);
  })
  .finally(() => {
    console.log('Promise is settled');
  });
JavaScript

Chaining Promises

One of the powerful features of Promises is their ability to chain multiple asynchronous operations. Each .then() returns a new Promise, which allows for chaining.

let promise = new Promise((resolve, reject) => {
  resolve(1);
});

promise
  .then(result => {
    console.log(result); // 1
    return result * 2;
  })
  .then(result => {
    console.log(result); // 2
    return result * 3;
  })
  .then(result => {
    console.log(result); // 6
  });
JavaScript

Promise.all and Promise.race

Promise.all

The method takes an array of promises, and it returns a single promise: When every promise in the input array has fulfilled, this returned one fulfills, and it rejects if any of the input promises rejects.

Promise.all([promise1, promise2, promise3])
  .then(results => {
    console.log(results); // Array of results
  })
  .catch(error => {
    console.log('One of the promises rejected:', error);
  });
JavaScript

Promise.race

The Promise.race() method returns a Promise that resolves or rejects as soon as one of the input Promises resolves or rejects.

Promise.race([promise1, promise2, promise3])
  .then(result => {
    console.log('First resolved promise:', result);
  })
  .catch(error => {
    console.log('First rejected promise:', error);
  });
JavaScript

Creating Custom Promises

To unlock the full power of Promises, you’ll eventually need to learn how to create your own custom Promises. This involves the new Promise constructor and managing the resolve and reject functions.

function asyncOperation() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Operation complete');
    }, 1000);
  });
}

asyncOperation()
  .then(result => {
    console.log(result); // 'Operation complete' after 1 second
  })
  .catch(error => {
    console.error(error);
  });
JavaScript

Error Handling in Promises

It’s therefore often easier to handle errors in Promises than in callback-based code. With the help of .catch(), you can catch errors that are thrown in any part of the Promise chain.

new Promise((resolve, reject) => {
  throw new Error('Something went wrong');
})
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.error(error.message); // 'Something went wrong'
  });
JavaScript

Conclusion

Promises are an elegant, clean way of handling async operations in JavaScript. Understanding the basics of how promises work—states, chaining, and methods such as Promise.all and Promise.race—will help you write more efficient and readable asynchronous code. Promises are such a fundamental way JavaScript has been evolving: from modern web development with Promises to today, laying the groundwork for even more advanced features like async/await.

Frequently Asked Questions

1.What are the key benefits of using Promises over callbacks?

Promises reduce callback hell, making the code more readable and maintainable, and they introduce improved error handling and chaining of operations, making the overall result more readable and manageable.

2.What does the .finally() method do?

The .finally() method takes a single argument, which is a callback function that should be executed when a Promise is settled, whether fulfilled or rejected. This method can be used to execute any cleaning up operation or final action that is to occur after the Promise is completed.

3.What is the difference between Promise.all and Promise.race?

Promise.all waits for all the input Promises to fulfill before resolving with an array of their results or rejects immediately if any of the input Promises reject. Promise.race resolves or rejects the promise as soon as one of the input Promises resolves or rejects.