A life-long learner, adventure seeker, and front-end developer for Social.com at @salesforce

So, you've made a module/library/framework. It works and is easy to maintain but uses callbacks exclusively.

With the arrival of Promises, and huge adoption, isn’t it time that your module has a native implementation as well? You know, to reduce "callback hell."

Let's look at a simple example.

In order to execute this you’d do something like below.

This implementation is fine for the most part, but it only allows for the use callbacks. But when you already have callback hell you don’t want to add to it.

How do we fix this and allow the consumers of our module to use promises in addition to callbacks?

Our goal is to execute the function like below, which most people would agree is a little cleaner.

First, we need to pick a promise library/polyfill in case our environment (node or browser) doesn't have them implemented by default. I prefer bluebird, but there are many out there. You would implement it like below if you want to take advantage of native promises eventually.

Next, let's implement promises in a way that is backwards compatible. We don't want people who love their callbacks to get screwed by this update.

The code above allows for the use callbacks OR promises with the same function.

While this example is relatively small, it can be applied to almost any function you have already.

It's nice to give people a choice so they can implement your module in their own style. Could this possibly lead to more people using your module? Yes, of course.