Javascript Promises | What Is Promise In JavaScript

What Is Promise In Javascript

A promise is an object which represents the eventual completion or failure of an asynchronous operation. It is basically a returned object to which we attach callbacks, instead of passing callbacks into a function. Promises can be used to deal with asynchronous operations in JavaScript. They are preferred when dealing with multiple asynchronous operations where callbacks have the potential of creating callback hell leading to disturbing code. Before promises events and callback functions were in use but they had few functionalities and created unmanageable code. Many callback functions can create callback hell that leads to unmanageable code. And so, Events were not good at handling asynchronous operations.

Promises are the best choice for dealing with asynchronous operations in the most efficient and simplest manner. They can handle multiple asynchronous operations very easily and gives better error handling than callbacks or events. We can also say that promises are the ideal or the best choice for handling multiple callbacks at the same time, thus avoiding the undesired callback hell situation. Promises do provide a better scope for a user to read the code in a more efficient and effective manner especially if that particular code is used for implementing many or multiple asynchronous operations. 

A promise mainly has three states:

  1. Resolved
  2. Pending
  3. Rejected

It can be constructed using a constructor,

SYNTAX- var promise = new Promise(function(resolve, reject){

     //task to do

});

The constructor takes only one argument which is a callback function. The callback function takes two arguments namely resolve and reject. Then the task written inside is performed and if everything goes well then resolve is called or else reject is called.

With help of Promises, we can implement asynchronous actions ( dependant actions ) without using numerous nesting.

For example – 

let newPromise = new Promise(function(resolve,reject){

const x = “techStudy”

const y = “techStudy

if( x === y)

resolve();

else 

reject();

})

Promise.then(function(){

console.log(“Congrats, you’re a tech”);

})

.catch(function(){

console.log(“hard Luck”)

});

then() is invoked when a promise is either on resolve status or reject status. It can also be defined as a conveyer that takes data from the Promise and executes it successfully.

Inside then(), the first function is executed if the promise is in resolved mode and the result is received. The second one is executed if the promise is rejected and an error is received however it is optional.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *