A coder's digest that is trying to be quirky, flawed and an enormous success.

Node.js 8: util.promisify()

by Zubair Ahmed on September 29, 2017

Node.js 8 has a new utility function: util.promisify(). It converts a callback-based function to a Promise-based one. Since we are on this topic I would like to highlight one of the most straight forward explanation for promises that I have come across by Jecelyn Yeen

Imagine you are a kid. Your mom promises you that she’ll get you a new phone next week. You don’t know if you will get that phone until next week. Your mom can either really buy you a brand new phone, or stand you up and withhold the phone if she is not happy :(. Jecelyn Yeen

So now, what does util.promisify do?

In a very abstract way, it does the following:

Takes a function following the common Node.js callback style, i.e. taking a (err, value) => ... callback as the last argument, and returns a version that returns promises.

and

promisify(original) assumes that original is a function taking a callback as its final argument in all cases, and the returned function will result in undefined behaviour if it does not.

If you haven’t got it already, it basically, a utility function that takes a regular function and converts it to a function that returns a promise.

It has the following syntax:

constwait=(delay,callback)=>{/* … */};

The last parameter of the function passed to promisify must be a callback

The callback must follow Node’s callback style

But at the same time you can couple this with async to avoid the callback hell effectively!