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.