New Tutorials:   JAVASCRIPT    SASS/SCSS    PL/SQL  
CLOSE
   Promise  Javascript  Prototype Methods  
   Technology    Programming

Prototype Methods for Promise in Javascript with Examples

         
 AUGUST 17, 2018   by iamabhishek

In one of our last post, we discussed what is Promise and gave an introduction to various methods available to be used with Promise object.

In this article, we will dive deep into prototype methods of Promise object along with some good examples to muster a better understanding of promise and its use.

To revisit what a Promise object is, A Promise is a proxy for a value or data generally unknown at the time of creation of promise. Theoretically, we say, promise is an outcome of an async task, which is true, but not exclusive, because promise can also be used with synchronous tasks, but it surely doesn't make much sense to use it there.

We know how to create a Promise object and use the resolve() and reject() methods, if you missed that, please head back to our last article about promises in javascript.


Prototype Methods

There are 3 prototype methods available, they are:

1. then(onFulfilled, onRejected)

2. catch(onRejected)

3. finally(onFinally)

So let's get suited up and begin our deep dive into these methods.




Promise.prototype.then(onFulfilled, onRejected)

then() method is one of the most useful methods of Promise object. This method is called when a promise is resolved or rejected, in both the cases. In other words, we can say, then() method defines what to do once a certain task is performed, in this case, the promise is complete. This method takes two arguments, a callback for success(onFulfilled or resolved) and another for the failure case(onRejected). Both of these arguments are optional, so it up to you.

Also, there are many different ways(syntactic) to use this method, let's check out the one which is most commonly used.

// using both the arguments

promise.then(function(result) {

    console.log(result);  // It worked!

}, function(error) {

    console.log(error);  // It failed!

});

We can handle both success and failure using the then() method. Let's take a simple example where we will be creating a Promise object, and will add the prototype methods to it, one by one, starting with the then() method.

var isIt2019Yet = false;

// Promise object

var newSeasonOfGOT = new Promise(function(resolve, reject) {

    if(isIt2019Yet) {

        var newSeason = {

            series: 'Game of Thrones',

            season: '8'

        };

        resolve(newSeason);

    }

    else {

        var soLate = new Error('Wait till 2019');

        reject(soLate);

    }

});

The above code is easy to understand(even easier if you are a Game of Thrones fan).

We have a boolean isIt2019Yet, to define whether it's the year 2019 already.

Then we have a promise newSeasonOfGOT. The promise is either resolved if the new season is released, or else it is rejected with an error message.

Now let's see how we can consume the result of this Promise object using the then() method.

// defining the then() method

newSeasonOfGOT.then(function(fulfilled) {

    console.log(fulfilled);

}, function(err) {

    console.log(err.message);

});

As we can see above, then() method handling both resolved and rejected scenarios can become a bit confusing at times. So promise provides another method to handle the error situations, which is the catch().




Promise.prototype.catch(onRejected)

Rather than using then() method for handling both the success and failure of promise, we can use then() method to handle success and have the catch() method handle the error condition. This makes the code more readable. catch() method takes only a single argument.

Hence we can consume the result of the newSeasonOfGOT promise object as,

// then() method to handle success

// catch() method to handle error

newSeasonOfGOT.then(function(fulfilled) {

    console.log(fulfilled);  // successful resolution of promise

})

.catch(function(error) {

    console.log(error.message);  // rejected promise

})



Promise.prototype.finally(onFinally)

This method is executed at the end when the promise is completed, resolved or rejected, and the then() and catch() methods have been executed. In this method, we can keep the code which we want to execute at the end, no matter the promise gets successfully resolved or rejected.

Let's add the finally() method to our code.

// then() method to handle success

// catch() method to handle error

// finally() to execute at last

newSeasonOfGOT.then(function(fulfilled) {

    console.log(fulfilled);  // successful resolution of promise

})

.catch(function(error) {

    console.log(error.message);  // rejected promise

})

.finally(function() {

    console.log("We will keep waiting for Game of Thrones");

})

We hope this will clear your doubts around using various methods of the Promise object. If you have any doubt feel free to share them in the comment section below.


RELATED POSTS



Subscribe and receive amazing posts directly in your inbox.