JavaScript “Promises” — Simply Explained

Alwaz Qazi
2 min readAug 17, 2021

--

Photo by Andrew Petrov on Unsplash

JavaScript promises are same as the promises we make in real life. The commitment we make to someone.

Example:

“I promise I will code daily.”

Now this promise has two results.

  • You either fulfill it (resolved).
  • or You’ll break it. (rejected).

Now, let’s have a look at the syntax.

Syntax:

Promise syntax is super easy just like how we create a constructor. But here we pass a function with two parameters resolved(value) and reject(error).

Syntax of Promise

Example:

Here, we’ve made a promise that value of a=1+1 should be 2. If it is 2 then promise is resolved else it is rejected.

Now, let’s learn how we can interact with these promises.

Here, we will use two methods to check whether our promise has resolved or rejected.

  • then() will return resolved.
  • catch() will return rejected. as a callback message.

Benefits of using “Promises”.

  1. Improves code readability.
  2. Better handling of Async operations.
  3. Provides better flow of control while defining async logic.
  4. Better error handling.

Hope you got the concept of how Promises work. If you did please clap, follow and share.

Even if you didn’t, that’s fine you can do it anyway .😄

--

--