DEV Community

Cover image for Promise handling and chaining using async...await and then()...catch()

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

sudarshansb143 profile image Sudarshan Sawandkar ・3 min read


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 
    .then(response => console.log("User Login is ",
    .catch(err => console.log("error", err.message))
Enter fullscreen mode Exit fullscreen mode

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("")
        console.log("user login is ",
    } catch (error) {
        console.log("error ", error.message)
Enter fullscreen mode Exit fullscreen mode

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
    .then(response => {
        console.log("User Login is ",
        console.log("calling second one\n ")
        //next call 
            .then(data => console.log("\n success \n"))
            .catch(err => console.log("err 2"))
    .catch(err => console.log("error", err.message))
Enter fullscreen mode Exit fullscreen mode

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("")
        let resp2 = await axios.get("")
    } catch (error) {
        console.log("error ", error.message)
Enter fullscreen mode Exit fullscreen mode

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(""),axios.get("")])
        console.log("\n done with then \n")
    } catch (error) {
        console.log("error ", error.message)

Enter fullscreen mode Exit fullscreen mode

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 :) πŸ‘»

Discussion (2)

tboss09 profile image
Akosile Oluwatayo Samuel

Definitely learnt something new today

sudarshansb143 profile image
Forem Open with the Forem app