Promises in JavaScript

Prachi
2 min readOct 6, 2020
Photo by Galina N on Unsplash

If you have not read about callbacks, I strongly recommend you to read about callbacks in JS. Callbacks in JS

Promises in JavaScript are just like promises that you make in real life. It has 3 states-

  1. Pending:-When a promise is created
  2. Resolved: When you have fulfilled your promise
  3. Rejected: When you have not fulfilled your promise

A promise is an object that does an asynchronous operation and notifies when it’s done. It’s like you have promised someone to do something, so when it's done you will notify the user that it is fulfilled, but if you failed to fulfill it, in this case too you will notify the user.

Let’s create Promises and understand its working-

Create Promise

The Promise is created using the new keyword and contains the ‘Promise’. Since we are using the ‘new’ keyword, it defines that we are creating an object.

It takes a function as an argument. This function two callbacks: one for notifying when the operation is successful (resolve) and one for notifying when the operation has failed (reject).

Let’s create a promise:

In the above example if the weather is true we are fulfilling the promise i.e resolving it and returning the object ‘obj’, else we are rejecting it and returning ‘Bad weather no Date!’.

Let’s use Promises.

Using Promises

Remember two points-

  1. Whatever you are passing as an argument inside resolve() will be received inside then().
  2. Whatever you are passing as an argument inside reject() will be received inside catch().

Taking the above example-

You will get the result-

If weather = false, the result will be-

Thank you for reading! 🌺🙏

--

--