šŸ¤JavaScript PromisesšŸ¤

šŸ¤JavaScript PromisesšŸ¤

Promises are a broad topic so I can't go into every detail in this article.šŸ¤— But you'll find an overall introduction to what Promises are, explanations of terms like resolve, reject, and chaining, and a code example for creating and using Promises.

Theoretically, JS promises are no different than real-life promises ā€” when coupled with result-oriented conditions.

mom I promise to clean my room.png

A promise is an action that guarantees a result in the future, the result could be the expected one(positive) and if anything goes wrong, the result will be something that was not anticipated(negative). So, while making the promise we also close on the conditions ā€” what if:

  • If Jon is able to clean his room(fulfilling the promise condition): He goes out for football!!
  • But what if he does not clean(failing to complete the promise condition): he needs to bring groceries.

In JavaScript, a promise is a good way to handle asynchronous operations. It is used to find out if the asynchronous operation is successfully completed or not.

What is a Promise in JavaScript?šŸ¤”

A promise is an asynchronous action that may complete at some point in the future and produce a value. This value is not necessarily known at the time of its creation. Once the value is produced, it notifies the user.

Promises provide a robust way to wrap the result of asynchronous work, overcoming the problem of deeply nested callbacks.

A JavaScript promise is created with the help of the new keyword.

Hereā€™s the general syntax

let some_action = new Promise(function(resolve, reject)

{

  // Perform some work

})

States of PromisesšŸ¤

A promise can be:

  • āœ…Resolved or Fulfilled: ā€“ A promise is resolved if its result is available. Simply means something is finished and all went well. (onFullfilled() will be called) e.g., resolve() was called.
  • āŒRejected: ā€“ A promise is rejected if an error happened. (onRejected() will be called) e.g., reject() was called.
  • ā³Unresolved or Pending: ā€“ A promise is pending if the result is not ready. That is, its waiting for something to finish first. (e.g., an asynchronous operation)
  • Settled: ā€“ A promise is settled if itā€™s not pending i.e. when it is resolved or rejected. A settled promise is immutability i.e. once settled a promise canā€™t be resettled.

Promise.png

What is Chaining?ā›“ļø

Callback functions have been used alone for asynchronous operations in JavaScript for many years. But in some cases, using Promises can be a better option.

If there are multiple async operations to be done and if we try to use good-old Callbacks for them, weā€™ll find ourselves quickly inside a situation called callback hell problem. :

[firstRequest(function(response) {  
    secondRequest(response, function(nextResponse) {    
        thirdRequest(nextResponse, function(finalResponse) {     
            console.log('Final response: ' + finalResponse);    
        }, failureCallback);  
    }, failureCallback);
}, failureCallback);

However, if we handle the same operation with Promises, since we can attach Callbacks rather than passing them, this time the same code above looks much cleaner and easier to read:

firstRequest()
  .then(function(response) {
    return secondRequest(response);
}).then(function(nextResponse) {  
    return thirdRequest(nextResponse);
}).then(function(finalResponse) {  
    console.log('Final response: ' + finalResponse);
}).catch(failureCallback);

The code just above shows how multiple callbacks can be chained one after another. Chaining is one of the best features of Promises.

Creating and Using A Promise.šŸ¤

Letā€™s take an async function as given below

function async_fn() {
  setTimeout(function(){
    console.log("executed");
  }, 1000);
}

Now if we want to return something from async_fn, we have two options:

  • Use a callback function
  • Use promise

The disadvantage of the first approach is that it leads to a callback hell problem.

Now, letā€™s see how this issue can be solved using promises. To create a promise we use the below given syntax

new Promise((resolve, reject)=>{
  if(success){
    resolve("success");
  } else {
    reject("failed");
  }
});

Example:

function timer() {
  return new Promise((resolve, reject)=> {
    setTimeout(()=>{
      resolve("Timeout");
    },2000);
  });
}

Promise provides three methods, to consume promise and handle the result

  • then: if promise results in success, then method callback is called
  • catch: if promise fails, catch method callback is called
  • finally: method callback is called when the promise is fulfilled either in success or failure. Can be used for common tasks such as hiding the loader etc.

Now, letā€™s see how to consume a promise in the following example:

timer().then((response)=>{
  // function returned in success
  console.log(response);
}).catch((error)=>{
  // function returned in error
  console.log(error);
}).finally(()=>{
  // always called
  console.log("Promise completed");
});

then( ) for resolved Promises:

If you revisit the picture at the beginning of this post, you'll see that there are 2 cases: One for resolved promises and one for rejected. If the Promise gets resolved (success case), then something will happen next (depending on what we do with the successful Promise).

myPromise.then();

The then( ) method is called after the Promise is resolved. Then we can decide what to do with the resolved Promise.

For example, letā€™s log the message to the console that we got from the Promise:

myPromise.then((message) => {  
    console.log(message);
});

catch( ) for rejected Promises:

However, the then( ) method is only for resolved Promises. What if the Promise fails? Then, we need to use the catch( ) method.

Likewise, we attach the then( ) method. We can also directly attach the catch()method right after then( ):

myPromise.then((message) => { 
    console.log(message);
}).catch((message) => { 
    console.log(message);
});

So if the promise gets rejected, it will jump to the catch() method, and this time we will see a different message on the console.

Wrap UpšŸŽ

So this is how we create a Promise in JavaScript and use it for resolved and rejected cases. Promises are a broader topic, and there are many more things to learn about them. So understanding how they work takes time.

This post is just an introduction to Promises, and I hope you found it helpful for getting an idea about what JavaScript Promises are and how to use them.

Thank you for reading!ā¤ļøā¤ļøā¤ļø

Did you find this article valuable?

Support Chhakuli Zingare by becoming a sponsor. Any amount is appreciated!

Ā