Promises in Javascript

Promises in Javascript

Promises in Javascript

The Promise object represents an asynchronous operation’s eventual completion (or failure) of an asynchronous operation and its resulting value.

A Promise is used to handle async operations in javascript. It is a proxy when a promise is made, which means the value of pledges may be unknown. It allows you to associate handlers with an asynchronous action’s success value or failure reason. For example, it will enable an asynchronous function that takes its time and return the value. After that, the promise is filled with this value. 

State of Promises: 

A promise has three states from creation until it returns value or error. Below are the state of the pledges:  

    • Pending state: This is the initial state when a promise is created, and it is waiting to get either value or some error. This is just after creation when nothing is returned to promise.
    • Fulfilled state: This is the state where a promise gets resolved and returns a success value.
    • Rejected state: This is also one of the final states. It means promises are not completed successfully, and it throws some errors.

The pending state promise will be either a fulfilled state or rejected state. Promises are eventual completion or failure, so either it will return some value or throw some error. 

We attach an inbuilt javascript method with a promise to get this value. So, when contracts are rejected or fulfilled, it automatically .then ( )  will be called, storing the value.

Once promises are created, the state becomes pending, but it can not be forever. Because a promise has to be resolved eventually, and either it will return a success or a failure value.

new Promise((resolveFirst) => {

  resolveFirst(

    new Promise((resolveSecond) => {

      setTimeout(resolveSecond, 1000);

    })

  );

});

The resolveFirst is called synchronously to get its value instantly, but the matter will not be filled. Because resolveFirst is called with resolveSecond. Therefore the promise will not be loaded. However, it will be served after 1 second when resolveSecond will return value. 

Promise Chaining: 

Promise chaining allows us to chain multiple asynchronous methods (functions) dependent on each other. So, once the first asynchronous function is resolved, only the second one can be resolved.

Javascript provides us with some inbuilt functionality. For example, .then ( ), .catch ( ), finally ( ). These are used to associate the following async function when that promise is settled. This method return promise so they can be chained.

The .then() method takes up to two arguments, the first is a callback function for the fulfilled case of the promise, and the second is a callback function for the rejected case. Each .then() method returns a newly generated promise object, which can optionally be used for chaining.

const myFirstPromise = new Promise((resolve, reject) => {

  setTimeout(() => {

    resolve(“hello”);

  }, 300);

});

myFirstPromise

  .then(handleFulfilledA, handleRejectedA)

  .then(handleFulfilledB, handleRejectedB)

  .then(handleFulfilledC, handleRejectedC);

Processing continues to the following link of the chain even when a .then() lacks a callback function that returns a Promise object. Therefore, a chain can safely omit every rejection callback function until the final .catch().

So, we require that error be handled immediately then we should throw the error state down. But if it is unnecessary, it will be automatically caught in the .catch(..) method. A .catch()  method is similar to the  .then() method. But it can have a callback function if the promises get fulfilled.

myFirstPromise

  .then(handleFulfilledA)

  .then(handleFulfilledB)

  .then(handleFulfilledC)

  .catch(handleRejectedAny);

 

The termination condition of a promise determines the “settled” state of the following promise in the chain. A “fulfilled” state indicates a successful completion of the promise, while a “rejected” state indicates the failure of the promise. The return value of each fulfilled promise in the chain is passed along to the next .then(), while the reason for rejection is passed along to the next rejection-handler function in the chain.

Promises concurrency: 

The Promise class offers four inbuilt static methods to facilitate async tasks.

    • Promise.all( .. ): 

It will return success when all the promises are fulfilled. However, if any of the passed promises return rejected value, then Promise.all (..) will be rejected.  

    • Promise.allSettled( .. ) : 

It is similar to Promise.all(..) but does not see the final state of promise. Instead, it will just see if promises are set or not. If all the passed promises are set, then Promise.allSettled(..) will be fulfilled; otherwise, not.

    • Promise.any ( ):

Promise.any(..) is nearly opposite to Promise.all(..). It will be fulfilled when any of the passes async methods are fulfilled. It will only be rejected when all the promises are getting rejected.

    • Promise.race( ):

It is nearly the opposite of Promise.allSettled(..). It will be set if any of the passed promises is set. It is fulfilled when any of the promises are fulfilled and rejected if any of the promises get rejected.

Summary
Article Name
Promises in Javascript
Description
A Promises in JavaScript is used to handle async operations.It allows you to associate handlers with an asynchronous action’s success value or failure reason.
Author
Publisher Name
BugendaiTech Pvt Ltd
Publisher Logo
Spread the updates

Leave a reply



Notice: Undefined index: position_on_screen in /home/tl2jq5v7asif/public_html/wp-content/plugins/mystickyelements/mystickyelements-front.php on line 203