What is the Promise of Javascript and how to use it effectively?

What is the Promise of Javascript and how to use it effectively?

Table of contents

What is a promise

A promise is an Object that adds the callback functions once it gets resolved (success or failure) instead of passing the callback function as a parameter in the function. Basically with a Promise, we handle the asynchronous flow of JavaScript.

In traditional Javascript (before promise) we can handle asynchronous flow with callback functions where we can pass a function as a parameter in the function itself like below.

function foo(data, callback){
    callback(null, 'success');
}

foo(1, (err, res)=>{
    if(err){
        console.log(err);
    }
    console.log(res);
})

The callback function pattern may lead to a callback hell problem that you can see in the below code.

function giveOne(callback){
    callback(null, 1);
}

function giveTwo(callback){
    callback(null,2)
}

function giveThree(callback){
    callback(null,3)
}

giveOne((err,resOne)=>{
    giveTwo((err,resTwo)=>{
        giveThree((err,resThree)=>{
            console.log(resOne+resTwo+resThree);
        })
    })
})

To overcome this problem we must use a promise chaining.

function giveOne(callback){
    return new Promise((resolve,reject)=>{
        resolve(1);
    })
}

function giveTwo(preAns,callback){
    return new Promise((resolve,reject)=>{
        resolve(preAns + 2);
    })
}

function giveThree(preAns,callback){
    return new Promise((resolve,reject)=>{
        resolve(preAns + 3);
    })
}

giveOne()
    .then(res1=>{
        return giveTwo(res1);
    })
    .then(res2=>{
        return giveThree(res2);
    })
    .then(res3=>{
        console.log('ans ',res3);
    }).catch(err=>{
        console.log('final err ',err);
    })

So promise has three states 'pending', 'fulfilled, and 'rejected'. When Promise is created then it's in a 'pending' state.

When Promise is resolved successfully then it's in a 'fulfilled' state.

When Promise is a failure due to some reason then it will be 'rejected' for 'failure' state.