DEV Community

Alwaz Qazi
Alwaz Qazi

Posted on

JavaScript “Promises” — Simply Explained

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).

Image description

Example:
Image description

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.

Image description

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 a 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 follow and share.

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

Discussion (0)