In this guide you will learn how to use Node’s util.promisify
to promisify your own functions. This utility function was included in NodeJS version 8. If you plan to follow along with this guide you’ll need to install the latest version. As an added bonus I also show you how to use promisify
with await
and async
.
TLDR;
util.promisify
converts a regular function into an async function, i.e. a function that returns a promise- The function passed to
util.promisify
must follow the NodeJS callback style. The function must pass a callback as the last parameter, and the callback must be the take the following parameters in the following order:(err, value) => { /* … */ }
- Promisified functions can be used with
await
andasync
to help avoid messy promise chains and introduce a cleaner, saner, way to do asynchronous programming.
What does util.promisify do?
The official node documentation says:
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 thatoriginal
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.
So basically it’s a utility function that takes a regular function and converts it to a function that returns a promise/s.
The function passed to util.promisify
has to follow a couple of conventions:
- The final parameter of the function passed to
promisify
must be a callback. - The callback must follow Node’s callback style.
Here is an example of a valid function: