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
1 2 3 4 5 |
const dns = require('dns'); dns.resolve('arjunphp.com', 'MX', function(err, addresses) { if(err) throw new Error(err); console.log(addresses) }); |
In this above example, you can see that, we are getting response in callback style. Now lets convert it to Promise
1 2 3 4 5 |
const util = require('util'); const dnsResolveAsync = util.promisify(dns.resolve); dnsResolveAsync('arjunphp.com', 'MX') .then(addresses => console.log(addresses)) .catch(err => console.log(err)); |
Or, equivalently using async functions:
1 2 3 4 5 6 7 8 9 |
const util = require('util'); const dnsResolveAsync = util.promisify(dns.resolve); async function getMxRecord() { const addresses = await dnsResolveAsync('arjunphp.com', 'MX'); console.log(addresses); } getMxRecord(); |
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.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.
thx)
10x!