Today we going to take a look at how to handle async code in nodejs using Promises.
While doing projects, we all have to use promises at some point of time sooner or later. regardless of what type of API we use, (whether it is 3rd party API like mentioned above or your own back end API) Promises are always Swiss army knife's for us.
As of now, many HTTP libraries gives us the elegant way to handle async code using promises, the Axios is my preferred candidate. Because, it gives us the flexibility and provides built-in support for many things like promises.
While handling promises, it primarily have to three states of of execution where it lives once we started Promise execution.
Pending --> Currently executing
Resolved --> Executed successfully
Rejected --> Failed to Execute
let fakeAsyncCall = (ms) => {
return new Promise((resolve, reject) => {
try {
setTimeout(() => {
console.log("executed at", Date());
resolve(true);
}, ms);
} catch (error) {
console.log("err", error.message)
reject(false)
}
});
};
Above snippet returns the value as true by using the callback function resolve the promise if the timeout executed successfully else it will reject it with false value.
This is the basic implementation of promises, we can replace setTimeout() with any API call.
//calling fakeAsyncFunction()
fakeAsyncCall()
.then( data => console.log("success"))
.catch(err => console.log("Promise failed"))
This is how we execute handelAsynCall(). As it returns the Promise object, we are handling Promise using then.... catch block.
(we can use async --- await also)
So, then() block executes if promise is resolved successfully otherwise catch() block is executed if any exception occurs.
** Final Thoughts **
I hope this post will help someone to gain better understanding regarding promises.
if you liked the post, please consider sharing it.
Thank you
Top comments (0)