JavaScript Promise

Promises are one of the ways to deal with asynchronous operations in JavaScript

Promises are hard to understand and broad topic. We are not going into every single details, just trying to explain basic understanding in easy words.

Promise, promise a result!

A Promise is an object that may produce a value some time in the future. this can be a resolved value or a reject value (in case of any error).

Promises may have 3 possible states.

  1. Pending: An Initial state before the promise succeeds or fails
  2. Resolve: Promise Complete
  3. Reject: Promise Failed

 



let promise = new Promise(function(resolve, reject) {
  resolve(); // when successful
  reject();  // when error
});

promise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

when we request data from the server by using a Promise, it will be in pending mode until we receive our data.

If we achieve to get the information from the server, the Promise will be resolved successfully. But if we don’t get the information, then the Promise will be in the rejected state.

If there are multiple requests, then after the first Promise is resolved (or rejected), a new process will start to which we can attach it directly by a method called chaining.

The .then  method takes up 2 arguments, the first argument is callback function for resolved case of promise and second argument is callback function for reject case.

Each .then method returns a new promise object which may used for chaining.


promise.then(callbackResolvedA, callbackRejectedA)
  .then(callbackResolvedB, callbackRejectedB)
  .then(callbackResolvedC, callbackRejectedC)
  .then(callbackResolvedD, callbackRejectedD);

This article is just for introduction of promises in JavaScript.

Hope you will find this helpful, write us below to improve article.

Thank you for reading :)

Leave a comment

your email address will not be published. required fields are marked *

Name *
Email *
Phone