Promise handling and chaining using async…await and then()…catch()

TL:DR

Handling promises is one of the biggest topics in the nodejs. But, in this article I will try to explain the various ways to perform promises operation (including chaining) using both async…await and then()…. catch().

In Nodejs we all us…


This content originally appeared on DEV Community and was authored by Sudarshan Sawandkar

TL:DR

Handling promises is one of the biggest topics in the nodejs. But, in this article I will try to explain the various ways to perform promises operation (including chaining) using both async...await and then().... catch().

In Nodejs we all use promises to handle the async code like Third Party API calls, Tedious I/O Operations and other CPU intensive tasks, which are blocking.

While handling this kind of code we have to decide the approach to handle promise afterwards once it is resolved or reject. For that we can use mainly two ways.

1. ? Using then() .... catch() :



It pretty simple to handle the promise in then() - catch() block. then() block will handle resolved promise and catch will handle reject promise.

//Handle Promise using then ---- catch 
axios.get("https://api.github.com/users/sudarshansb143")
    .then(response => console.log("User Login is ", response.data.login))
    .catch(err => console.log("error", err.message))

2. ? Using async .... await :



This is the second approach where we will write external try catch to handle any unwanted behavior of promises and smoothly catch errors.

//Handle Promise using async ---- await 
(async () => {
    try {
        const axios = require("axios")
        let response = await axios.get("https://api.github.com/users/sudarshansb143")
        console.log("user login is ", response.data.login)
    } catch (error) {
        console.log("error ", error.message)
    }
})()

As await needs to be wrapped inside async function I uses IEF (more on this later)

Until now it is pretty simple but, now take a look at following code (unoptimised)

//handle multiple promises with then --- catch
axios.get("https://api.github.com/users/sudarshansb143")
    .then(response => {
        console.log("User Login is ", response.data.login)
        console.log("calling second one\n ")
        //next call 
        axios.get("https://api.github.com/users/sudarshansb143")
            .then(data => console.log("\n success \n"))
            .catch(err => console.log("err 2"))
    })
    .catch(err => console.log("error", err.message))

Here, I am handling the multiple promises one after another. So, first I fetched my own GitHub profile. Once data is available I again executed promise and then logged the "success" message for confirmation that second promise is resolved successfully

Similar code can be written with async...await as

//handle multiple promises with async --- await
async function handleMultiplePromisesWithAsync() {
    try {
        let resp1 = await axios.get("https://www.api.github.com/users/sudarshansb143")
        let resp2 = await axios.get("https://www.api.github.com/users/sudarshansb143")
        console.log("done")
    } catch (error) {
        console.log("error ", error.message)
    }
}
handleMultiplePromisesWithAsync()

Anyone looking at both snippet will easily able to decide that the async... await code is pretty straight forward instead of multiple then catch block. This is once of difference why I prefer the async....await other ways.

Also, we have to use less curly bracers in async.... await ??

? Chaining Multiple Promises using Promise.all() ?

As mentioned above, the simultenous API calls can be done one after another but there is other elegant way of performing the same task

async function usePromiseAll() {
    try {
        await Promise.all([axios.get("https://api.github.com/users/sudarshansb143"),axios.get("https://api.github.com/users/sudarshansb143")])
        console.log("\n done with then \n")
    } catch (error) {
        console.log("error ", error.message)
    }
}

usePromiseAll()

Here, I am resolving the multiple promises using single .all() block. But, keep in mind both promises will be resolved at once hence, there should be no inter dependent code is written afterwards.

For scenario where input of next promise is dependent on output of previous promise, we must use separate await / then() blocks

# ? IEF :-

This are the function which are executed immediately once we call the script use command node. Anyone using IEF must care about it's consequences on the other stuff present inside the similar script. Because, there is possibility that the code considers the other code as intermediate object

⚡ Final Thoughts ⚡:

Using async...await / then()...catch() is totally the prefrential constraint. So, everyone has their own approach to handle and write the code. Hence, this is my try to explain what I think about them

? Thanks For Reading....

? Please let me know your thoughts in comments :) ?


This content originally appeared on DEV Community and was authored by Sudarshan Sawandkar


Print Share Comment Cite Upload Translate
APA
Sudarshan Sawandkar | Sciencx (2022-10-06T01:10:52+00:00) » Promise handling and chaining using async…await and then()…catch(). Retrieved from https://www.scien.cx/2021/04/30/promise-handling-and-chaining-using-async-await-and-then-catch/.
MLA
" » Promise handling and chaining using async…await and then()…catch()." Sudarshan Sawandkar | Sciencx - Friday April 30, 2021, https://www.scien.cx/2021/04/30/promise-handling-and-chaining-using-async-await-and-then-catch/
HARVARD
Sudarshan Sawandkar | Sciencx Friday April 30, 2021 » Promise handling and chaining using async…await and then()…catch()., viewed 2022-10-06T01:10:52+00:00,<https://www.scien.cx/2021/04/30/promise-handling-and-chaining-using-async-await-and-then-catch/>
VANCOUVER
Sudarshan Sawandkar | Sciencx - » Promise handling and chaining using async…await and then()…catch(). [Internet]. [Accessed 2022-10-06T01:10:52+00:00]. Available from: https://www.scien.cx/2021/04/30/promise-handling-and-chaining-using-async-await-and-then-catch/
CHICAGO
" » Promise handling and chaining using async…await and then()…catch()." Sudarshan Sawandkar | Sciencx - Accessed 2022-10-06T01:10:52+00:00. https://www.scien.cx/2021/04/30/promise-handling-and-chaining-using-async-await-and-then-catch/
IEEE
" » Promise handling and chaining using async…await and then()…catch()." Sudarshan Sawandkar | Sciencx [Online]. Available: https://www.scien.cx/2021/04/30/promise-handling-and-chaining-using-async-await-and-then-catch/. [Accessed: 2022-10-06T01:10:52+00:00]
rf:citation
» Promise handling and chaining using async…await and then()…catch() | Sudarshan Sawandkar | Sciencx | https://www.scien.cx/2021/04/30/promise-handling-and-chaining-using-async-await-and-then-catch/ | 2022-10-06T01:10:52+00:00
https://github.com/addpipe/simple-recorderjs-demo