Promise handling in javascript, best approach.

Promise handling in javascript, best approach.

INTRODUCTION

In this article we will discuss which approach is best inorder to handle the promises in Javascript. Our focus will be readability and maintainability There is two approach to handle the promises in Javascript

1. Try/Catch with Async await

2. Then/catch

Let's create a Promise

First thing first , let's create two promises so that we can apply both methods on it

function makeRequest(location) {
    return new Promise((resolve,reject) => {
        console.log(`Making Request to ${location}`)
        if(location === 'Google')  {
            resolve('Google says hi')
        } else {
            reject('We can only talk to Google')
        }
    })
}

function processRequest(response) {
    return new Promise((resolve, reject) => {
        console.log('Processing response')
        resolve(`Extra Information + ${response}`)
    })
}

Promise handling using Then/catch

makeRequest('Google').then((response) => {
    console.log('Response Received')
    return  processRequest(response)
}).then((processedResponse) => {
    console.log(processedResponse)
}).catch(err =>{
    console.log(err)
})

Promise handling using Try/Catch with Async await

async function doWork(){
    try{
    const response = await makeRequest('Google')
    console.log('Response Received')
    const processedResponse = await processRequest(response)
    console.log(processedResponse)
    } catch (err){
        console.log(err)
    }
}

doWork();

Conclusion

Clearly , Try/Catch with Async await is more clean and easy to understand whereas nested .then are too complicated