Posted on Arjun

Node Js – convert a callback-based function to a Promise-based one?

In this post you will learn how to convert a callback-based function to a promise-based one using util.promisify() function.As a part of Node Js version 8, promisify() function added to util module.

In simple worlds util.promisify() function converts a regular function into a promise. The final paramter of the function passed to promisify must be a callback and it should follow Node’s callback style. i.e. taking a (err, value) => ... callback as the last argument, and returns a version that returns promises.

Example

In this above example, you can see that, we are getting response in callback style. Now lets convert it to Promise

Or, equivalently using async functions:

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.
DMCA.com Protection Status