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 :) 👻
Top comments (1)
Thanks