Promise In Javascript

A Promise in Javascript is a very special object and I think you should know it especially if you are preparing for an interview.

So the first thing to know is that as the name suggests "Promise" is like an agreement that something will happen at some point of time (which you do not know right now) in future and when it happens you want your code to do something.

A promise is a special object which returns the result after an asynchronous activity such as API call is complete.

A promise can be in any of these three states at a time

  • Pending (example: API call still in progress)
  • Fulfilled (example: API call finished successfully)
  • Rejected (example: API call failed)

So if go by the API call example an API may or may not be successful always. Sometimes it may fail due to reasons such as server crash or network issue or authentication failure etc. But you do not want to stop the execution of your javascript code on your browser till the code gets completed. So what you do it you define a Promise and perform your asynchronous task inside it then you move on. 

As soon as your asynchronous task is complete your promise will either enter rejected OR fulfilled state.

How to define a promise?

A promise can be defined using Promise constructor like this new Promise((resolved, reject) => {})

Like given above you call the Promise constructor and pass a callback function as argument which has two parameters i.e reject, resolve. inside this callback function, you perform your tasks and call either reject or resolve in it. 

    
        var isTrue = true;
        var promise = new Promise((resolve, reject) => {
            if(isTrue)
                resolve();    
            else        
                reject();}
            )
    

Congratulations! you have just created a new javascript promise which is obviously going to be fulfilled (duh!). But how to use it? 🤔

Now the promise object provides you methods like then(), catch(), finally() to consume (use) it.

then() method accepts two functions as arguments. the first one gets executed when a promise is resolved and the second one is when it is rejected. Here is an example.

    
    function createAPromise(flag) {    
        return promise = new Promise((resolve, reject) => {        
            if(flag) {            
                resolve();        
            } else {            
                reject();        
            }    
        }); 
    }
    createAPromise(true).then(
        response => console.log('yay!! my promise fulfilled'),    
        error => console.log('Why!! my promise got rejected :(')    
    ); 

    //the result would be 'yay!! my promise fulfilled'
    

There is another way to handle rejection of your promise. And that is using the Catch method.

The catch method takes a callback function as its only parameter and it calls it when your promise is rejected.

Carry forwarding the previous example.

    
    createAPromise(false)
    .then(response => console.log('yay!! my promise fulfilled'))
    .catch(error => console.log('Why!! my promise got rejected :('));

    // result will be 'Why!! my promise got rejected :('
    

Now, what if you want to perform some task no matter what the result of the promise is. And that's where we use the Finally method.

The "finally" method takes a callback function as its parameter and it will always execute that function no matter what the result of your promise is. 

    
        //when promise is fulfilled
        
        createAPromise(true)
        .then(response => console.log('yay!! my promise fulfilled'))
        .catch(error=> console.log('Why!! my promise got rejected :('))
        .finally(()=>{    console.log('finally my promise has finished')});

        //the result would be
        yay!! my promise fulfilled
        finally my promise has finished

        //when promise is rejected
        createAPromise(false)
        .then(response => console.log('yay!! my promise fulfilled'))
        .catch(error=> console.log('Why!! my promise got rejected :('))
        .finally(()=>{ console.log('finally my promise has finished')});

        //the result would be
        Why!! my promise got rejected :(
        finally, my promise has finished
    

So as you can see the callback function you passed to finally method is always called. There are few more promise methods such as Promise. allPromise.race but we will discuss them some other time. 

Thank you for reading.

reference mozilla docs