Adding Promise Support to a Node.js Library

Sharing is Caring

I know that when I am working in JavaScript, I prefer to keep everything to using promises or async/await instead of occasionally using callbacks because a library doesn’t support them.

Promises vs Callbacks

This has the makings of a religious war, but it doesn’t have to be. Callbacks are great, and they make a lot of sense for very small scripts or applications. I have no problem using them, but they become difficult to use and understand if someone structured their library to use different functions.

Promises allow us to avoid having deep indentations to handle callbacks. I know that typically I end up four or five callbacks in and end up confused on what’s going on when I’m trying to debug something I wrote or another team member wrote months ago.

So, how do we convert callbacks to use promises?

There are a few different ways to convert callbacks to use promises. In the built-in util package, there’s a function called promisify() that allows us to convert a standard callback function into a promise based function.

An a version with a callback would look something like this:

The code would look something like this:

As you can see, we’ve promisified one function meaning that we would need to potentially do this for everything in fs if we were extensively using it. This isn’t necessarily ideal for a library that we might be heavily depending on.

Libraries like bluebird allow us to potentially promisify the entire library. Out of the box it works by appending “Async” on the end of the function. Here’s an example:

As you can see, this is very easy to do but it’s a lot of overhead if we’re only using one function. Bluebird is a separate library which has its own dependencies.

If you are already using Bluebird for some of the features not in native promises, it’s probably okay to use it promisify libraries. I wouldn’t personally add it just to promisify libraries.

Also published on Medium.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.