JavaScript Promises

JavaScript Promises manage asynchronous operations, allowing for cleaner, more readable code execution.

javascript-promises

JavaScript Promises in Detail.

JS Promises:

JavaScript is a single threaded, two bits of script cannot run at the same time; they have to run one after another. Promises are used to handle asynchronous operations in Javascript. They are easy to manage when dealing with multiple async operations where callback can create callback hell leading to unmanageable code A Promise is object that keep track about whether a certain event has happened already or not Determines what happens after the events has happend.

JS Promises | States

A JavaScript Promise object can be:

  • Pending
  • Fulfilled
  • Rejected

Pending:

Initial state, neither fulfilled nor rejected. I working, the result is undefined.

Fulfilled:

Operation completed successfully. The result is a value.

Rejected:

Operation failed. | The result is an error object.

JS Promises:

The .then() and .catch() methods are inbuilt callback functions that allow you to handle the resolved & rejected states of a promise, respectively.

Promise Syntax:

Let promise = new Promise((resolve, reject) => { //Executor }); resolve and reject are two callbacks provided by JavaScript itself.

resolve(value): If the job is finished successfully

reject(error): If the job fails

JS Promise Chaining:

Promise chaining in JavaScript allows you to execute a sequence of asynchronous operations in a specific order, one after another. It provides a clean and organized way to handle the results of each operation and pass them to the next one.

Attaching Multiple Handler:

You can add multiple handlers to a promise using the .then() method. Each .then() method can have its own success callback to handle the resolved state of the promise.

Like, Share and Subscribe #DevTools99 for more useful videos, tools info and #tutorials . Thank you!


DevTools99

Developer Co-Team

Let us make it easier for developers throughout the world to breathe. Let's keep things simple. Let's take it easy.