Thursday, October 17, 2024

JavaScript Promises

 Follow me


JavaScript Promises

Promises

A Promise is an object which is used to find out if the asynchronous operation is completed or not. "The code either executes or fails" in both cases user will be notified.


The Promise object has two properties: state and result.

State:

Pending: initial state, neither fulfilled nor rejected.

Fulfilled: meaning that the operation was completed successfully.

Rejected: meaning that the operation failed.

 

Result:

Undefined: we get this value when the promise is pending.

A result value: we get this value when the promise is fulfilled.

An error object: we get this value when the promise is rejected.

A promise is said to be settled if it is either fulfilled or rejected, but not pending.


Creating a Promise:

A Promise object is created using the new keyword and its constructor. This constructor takes a function, called the executor function, as its parameter.

This executor function takes two functions as parameters.

resolve - It is called when the task completes successfully and returns the results of the task as a value.

reject - It is called when the task fails and returns the reason for failure, which is typically an error object.

 


resolve & reject are built-in javascript callbacks. We can name them differently also like myResolve & myReject.


How to use a Promise:


When a promise is fulfilled, you can access the resolved data in the .then method of the promise.

When a promise is rejected (that is, the promise fails), you can access the error information returned in the .catch method of the promise

 


.then(): It can deal with the resolved case and rejected case also.

catch(): It deals with the rejected case only.


e.g :


Promise Chaining:

You can attach multiple handlers to a promise with the help of promise chaining which solves the problem of Callback() Hell.



No comments:

Post a Comment

Online Calculator

Follow Me 0 C % / * 7 8 9 - 4 5 6 +...