Promises in JavaScript

mrityunjaypalled

Mrityunjay-Palled

Posted on November 19, 2022

Promises in JavaScript

Promise is basically a JavaScript object that produces some result to represent the eventual completion or failure of an asynchronous operation. Before moving further some prior knowledge of asynchronous JavaScript is required. Let's take a look at the general syntax of promises.

Image description

JavaScript promises usually consist of producing code and consuming code. Producing code uses "resolve" and "reject" as arguments. On one side, "resolve" is called when the job is finished successfully. On the other, "reject" is called when we have some errors.Consuming code consists of ".then" and ".catch" blocks. The ".then" block is executed when the job is successfully completed. On the other side, ".catch" is executed when we have some errors.

Promise States:

  • pending: This is the initial state of Promise

  • fulfilled: Promise is said to be fulfilled when it is resolved

  • rejected: Promise is said to be rejected when we have some
    error while resolving

Image description

Implementing Promises:

Image description

Initially the promise will be in the pending state. As the consuming code is waiting for the result of producing code(either "resolve" or "reject") which is asynchronous in nature.

Image description

when the "if" condition becomes true, the promise gets resolved
after 2 seconds, now we can say the promise is fulfilled. The ".then" block of consuming code is executed, and the result will be logged to the console.

Image description

when the "if" condition becomes false, the promise gets rejected
after 2 seconds, now we can say the promise is in rejected state. The ".catch" block of consuming code is executed, and the result will be logged to the console.

Image description

💖 💪 🙅 🚩
mrityunjaypalled
Mrityunjay-Palled

Posted on November 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How JavaScript works
javascript How JavaScript works

November 8, 2024

A Beginner's Guide to JavaScript Closures
javascript A Beginner's Guide to JavaScript Closures

November 5, 2024

Type Coercion in JavaScript Explained
javascript Type Coercion in JavaScript Explained

November 18, 2024

Introduction to Asynchronous JavaScript
javascript Introduction to Asynchronous JavaScript

October 14, 2024

Strings -- Manipulating the Immutable.
javascript Strings -- Manipulating the Immutable.

November 15, 2024