JS Promises

JavaScript Promises are a modern approach to handle asynchronous operations. Although we can handle small small asynchronous operations using Callback Functions, but not large operations. Promises can handle long and nested asynchronous operations easily.

Promises are also helpful to handle long chaining of nested callback functions known as callback hell in javascript.

javascript promise
Javascript Promise

Promise States

A Promise is always in one of these states, pending, fulfilled and rejected. For chaining in Promise, we can use then or catch method.

Promise State Explanation
pending The initial state, waiting for fulfill or reject
fulfilled the operation has successfully done
rejected the operation was failed

A Promise is said to be resolved or settled when it is fulfilled or rejected. Once settled (resolved or rejected), a Promise cannot be changed. That means a Promise is immutable after settled.

The then() and catch() methods of Promise are used to handle callbacks that executes when it is settled or resolved.

Promise fulfilled

done


   
    function done(){
       console.log("done");
    }
    function error(){
       console.log("error");
    }
   
    var promise=new Promise((resolve,reject)=>{
        resolve();
        reject();
    });
    
    promise.then(done).catch(error);

Promise rejected

error found


   
    function done(){
       onsole.log("done");
    }
    function error(){
        throw new Error("error found")
    }
   
    var promise=new Promise((resolve,reject)=>{
        resolve();
        reject();
    });
    
    promise.then(done).catch(error);

In the above example, done and error are two callback functions. promise is a new instance of Promise Object with callback. There are two parameters of callback, resolve and reject.