JavaScript: Concept of Promise

 

Dear readers, this post is about a very useful and important concept of JavaScript. I think every beginner should have this basic knowledge while developing any project.

What is a Promise

In JavaScript, Promise is a very important concept.The Promise object represents the eventual completion or failure of an asynchronous operation and its resulting value.

👉🏻Promise is a proxy with an unknown value whenever a Promise is generated.
👉🏻 This allows the controller to connect with the final success value or reason for failure of the asynchronous operation.
👉🏻 This allows asynchronous methods to return the same values ​​as synchronous methods.
👉🏻Instead of returning the final value immediately, the asynchronous method returns a promise to provide the value at a particular point in the future.

Basic Syntax

Promise is a constructor function, so we need a new to create a Promise. It takes a function, as it's argument, with two parametersresolve and reject.
The syntax generally looks like:

const myPromise = new Promise((resolve, reject) => { } ) ;

States of a Promise
A promise has three states:

i) pending: It's the initial state, neither successful nor unsuccessful.
ii) fulfilled: It means that the operation was completed successfully.
iii) rejected: It indicates that the operation has failed.

Resolve Parameter
The resolve parameter is used when we want the promise to succeed.

Reject Parameter
The reject is used when we want to catch the failure.

The following is an example of a Promise:
const makeServerRequest = new Promise((resolve, reject) => {
  let responseFromServer;

  if (responseFromServer) {
    resolve("We got the Data");
  } else {
    reject("Data not Found");
  }
});

In the code snippet, responseFromServer represents a response from the server.

If responseFromServer is true, the resolve method will be called to successfully complete the promise and return the string as it's argument.

(Generally, it returns data)

Again, if responseFromServer is false, the promise will fail and call the reject method.

(Generally it catches the errors).


#viastudy

Post a Comment

0 Comments