DEV Community

Cover image for Handle async code in node.js using PROMISES
sudarshan
sudarshan

Posted on

2 2

Handle async code in node.js using PROMISES

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)
   }
  });
};

Enter fullscreen mode Exit fullscreen mode

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"))

Enter fullscreen mode Exit fullscreen mode

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay