Last updated on November 21, 2022
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 parameter 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
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 let’s convert it to Promise
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:
const util = require('util');
const dnsResolveAsync = util.promisify(dns.resolve);
async function getMxRecord() {
const addresses = await dnsResolveAsync('arjunphp.com', 'MX');
console.log(addresses);
}
getMxRecord();