JavaScript “Promises” — Simply Explained

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

--

--

--

I share what I learn.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to add less and svg support to Nextjs

Make your SVG images pop with a few lines of CSS

Progressive web apps(PWAs) are coming to a Safari near you

Developer Story: Logical Routing Module Design for a RESTful Server API

React Hook -Giving superpowers to functional components

vite build error

Use Node.js as its Own Build System

Generator for Algorithm Visualization

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alwaz Qazi

Alwaz Qazi

I share what I learn.

More from Medium

JavaScript: What is this..

Why JavaScript Promises are awesome

A quick review of Basic Math in JavaScript

JavaScript Array length — the definitive guide