Understanding Promises in Javascript

Prasad Sonawane
Nov 1, 2020 · 3 min read

We all know that javascript is a synchronous programming language but callback functions help to make it an asynchronous programming language.

By the Definition of Javascript, MDN Promises is,

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

Basically, promises are the same as real-life promises which we are making in real life.

Take an example, suppose you make a promise to your friends that are next weekend you will take them to a party.

But actually, you don't know you will get time on the weekend or not, means either you are going to complete that promise or maybe not.

So there may be below chances-

Pending: You don't know you will get time or not

Fulfilled: You gave them a party

Rejected: You don't give a party to them

So promise start with the pending state then after fulfilled and at the end it in the Rejected state.

There are 2 parts:

  1. Creation of promises
  2. Handling of promises
  3. Creation of Promises:
new Promise( //* executor*// function(resolve, reject) { ... } );

2.Handling Promises:

let partyPromise = true;
let giveParty = new Promise(function (resolve, reject) {
setTimeout(() => {
if (partyPromise) {
resolve(“I given party to friends”);
} else {
reject(“I am not given party to friends”);
}
}, 5 * 1000);
});

After execution of the above code below, you can see in the below snap there is the first state is pending state

Now after completion of 5 Seconds, it returns the below result that is a fulfilled state.

and after a changed of partypromise = true to false, it returns the below result

So the reject method moved the promises to the rejected() state.

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

promise object having static methods and prototype methods,

  1. Promise.prototype.then(onFulfilled, onRejected)
  2. Promise.prototype.catch(onRejected)
  3. Promise.prototype.finally(onFinally)
  4. Promise.prototype.then(onFulfilled, onRejected):

The then() the method is used to schedule a callback to be executed when the promise is successfully resolved.

2. Promise.prototype.catch(onRejected):

If you want to schedule a callback to be executed when the promise is rejected.

3.Promise.prototype.finally(onFinally):

It is used to execute the same piece of code whether the promise is fulfilled or rejected.

See below example :

function makePromise(partyPromise) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
if (partyPromise) {
resolve("I given party to friends");
} else {
reject("I am not given party to friends");
}
}, 5 * 1000);
});
}
let partyPromise = makePromise(true);
partyPromise
.then(success => console.log(success))
.catch(reason => console.log(reason))
.finally(() => console.log("Friends are ready for party !"));

Helpers Functions related to promises:

Promise.All

The Promise.all(iterable) the method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

Promise.race

The Promise.race(iterable) the method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.

Key points:

  1. Use promises whenever you are using async or blocking code.
  2. A promise is an object that returns a value in the future.
  3. A promise starts in the pending state and ends in either a fulfilled state or a rejected state.
  4. resolve maps to then and reject maps to catch
  5. If something needs to be done in both cases use .finally

Thank you for reading and feel free add comments and clap👋🏽
Hope this helps you.✌️

The Startup

Get smarter at building your thing. Join The Startup’s +741K followers.