DEV Community

Alwaz Qazi
Alwaz Qazi

Posted on

3

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post