I promise this way ‘PROMISE’ won’t break your heart in JavaScript 💔🫰 : Promises

Amitabh Mudgil
2 min readApr 10, 2023

--

Promise in JavaScript

Promise in JavaScript is quite similar to ‘promise’ in english language, according to definition in English.

Promise : “to say definitely that you will do or not do something or that something will happen”

This follows same on JavaScript as well, “Promise is an object that represents eventual completion or failure of an asynchronous operation” so one thing is for sure that it will return us something and that something can be completion or failure depend on operation.

Three States of Promise:

Pending : At initial stage promise is always found in pending state.

Resolved : If the value given in Promise is returned true.

Rejected : If the value given in Promise does not return.

A Promise is said to be settled or fulfilled if its either resolve or rejected but not pending, after being settled attached handler ( .then() or .catch() ) are called for the further execution of asynchronous operation.

This way JavaScript Synchronous operation still going on behind the scenes and Asynchronous operation would only proceed when promise is settled.

Promise Declaration : Promise is declared by “new Promise” and has two parameters i.e., Resolve & Reject passed at time of declaration.

Lets take a look at example:

const p1 = new Promise (function (resolve, reject) {
setTimeout (function () {

resolve(5);

}, 5000);

});

const p3 = new Promise (function (resolve, reject) {
reject("Ima reject the sh*t outta it");
});

p1.then ( function (value) {
console.log("P1 is settled YO!" + "",value);
});

p3.catch (function (v) {
console.log(v);
}); // to avoid the error in console or catch the error we use .catch ()

--

--

Amitabh Mudgil
0 Followers

JavaScript Developer | Thoughts into Words through Medium