What is a Promise in JavaScript

A promise is a special JavaScript object representing an asynchronous operation that may succeed or fail. It allows you to write code to handle both cases without using callbacks or blocking the execution. You can use methods like .then(), .catch(), and .finally() to chain promises and perform actions when they are settled.

Promises Object properties

The Promise is the proxy for the value not necessarily known when a promise is created. Thus, the promise allows you to associate the handlers with an asynchronous action’s eventual success or failure.

This lets asynchronous methods return the values like synchronous methods. Instead of immediately returning a final value, an asynchronous method returns a promise to supply value at some point in the future.

The Promise has one of the below states.

  1. Pending: An initial state or pending state, neither fulfilled nor rejected.
  2. Fulfilled: This means that the operation was completed successfully.
  3. Rejected: This means that the operation failed.

Constructor

The promise constructor takes in one argument: a callback function with two parameters called to resolve and reject. Thus, we can use promise as the two different approaches.

  1. Creating a Promise
  2. Consuming a Promise

How to create a Promise?

You can create a promise using the Promise constructor. It takes a function as an argument, called an executor, with two parameters: resolve and reject. The executor function runs when the promise is created and can call resolve or reject to settle the promise.

const prom = new Promise(function(resolve, reject) {
  setTimeout(() => {
    resolve('Promise is created and consumed');
  }, 200);
});

We created one javascript promise object and passed the two parameters to the Promise constructor called to resolve and reject.

At the time of consuming, if the promise is resolved, then we can consume the value using the then() function; if the promise is rejected, then we get the error values inside the catch() block.

How to consume a Promise?

To consume a promise, you can use methods like .then(), .catch(), and .finally(). These methods allow you to register functions that will be called when the promise is settled (either fulfilled or rejected).

The .then() method takes two functions as parameters: one for success and one for failure. It returns a new promise that can be chained with other promises.

The .catch() method takes one function as a parameter: one for failure. It returns a new promise that can be chained with other promises.

The .finally() method takes one function as a parameter: one that will be executed regardless of the outcome. It also returns a new promise that can be chained with other promises.

const prom = new Promise(function(resolve, reject) {
  setTimeout(() => {
    resolve('Promise is created and consumed');
  }, 200);
});

prom.then(value => {
  console.log(value);
});

Now, run the above file in node.js by typing the following command.

Javascript Promise Example Tutorial

The promise is also rejected; in that scenario, our code looks like the snippet below.

const prom = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('Promise is rejected');
  }, 200);
});

prom.catch(error => {
  console.log(error);
});

Output

Javascript Promise reject

So understanding promises are not that difficult if an excellent example is provided.

The executor initiates some asynchronous work typically and then, once that completes, either calls the resolve function to resolve a promise or rejects it if an error occurs.

The promise is rejected if the error is thrown in the executor function. The return value of the executor is ignored.

Promise Concurrency

Promise.all()

It returns the promise that is either fulfilled when all of the promises in the iterable argument have been fulfilled or rejected as soon as one of the promises in the iterable argument rejects the promise.

If the returned promise is fulfilled, it is fulfilled with an array of values from the fulfilled promises in the same order defined in the iterable.

If the returned promise rejects, it is rejected for a reason from the first promise in the iterable rejected.

Promise.race(iterable)

It returns the promise that fulfills or rejects, a.s.a. one of the promises in the iterable fulfills or rejects, with a value or reason from that promise.

Promise.reject(reason)

It returns the Promise object that is rejected for the given reason.

Promise.resolve (value)

It returns the Promise object that is resolved with the given value.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.