DEV Community

Cover image for Promises in JavaScript
Mrityunjay-Palled
Mrityunjay-Palled

Posted on

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

Top comments (0)