Promises in JavaScript

Promises in JavaScript

Promises are objects in JavaScript which returns a value which can be resolved or a reason for not being resolved.

States of promise:

There are 3 states of promise:

  1. Fulfilled
  2. Rejected
  3. Pending

Working of promises:

The initial state of a promise will be pending state. The function Promise will take two parameters resolve and reject as input. If the promise is successful then it calls the callback function for resolve and if the promise is not successful then calls the callback function forreject.

If a resolved value is being returned then .then() is executed and if reject is returned then .catch() is executed.

Creating a new Promise

A Promise object is created using the new keyword and its constructor Promise. This constructor takes a function, called the "executor function", as its parameter. That function in itself should take two functions as parameters. The first parameter resolve is called when the asynchronous task completes successfully and returns the results of the task as a value. The second parameter reject is called when the task fails, and returns the reason for failure, which is typically an error object.

Static methods of promise

1.Promise.all()

Waits for all the promises to be resolved or any to be rejected.

If the returned promise resolves, it is resolved with an array of all the values from the resolved promises, in the same order as defined.

If it rejects, it is rejected with the reason from the first promise as seen in example below.

2.Promise.allSettled()

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.

3.Promise.any()

Promise.any() takes an iterable of Promise objects. It returns a single promise that resolves as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected.

4.Promise.race()

The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.

5.Promise.reject()

The Promise.reject() method returns a Promise object that is rejected with a given reason.

6.Promise.resolve()

Returns a new Promise object that is resolved with the given value. If the value has a then method, the returned promise will "follow" that then, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.

So this is all about promises and its methods. I hope you got a better understanding of promises.

You can connect with me on twitter, linkedln.

Want to know what I do besides writing blogs checkout my Github.

Till next take care.....bye👋