Converting callback taking task into a promise

A callback is a function sent as an argument to another function. The callback is executed when a particular task is completed or when an event occurs. It is a predecessor to promises. Promises, though perform the same functionality as callback, are ,much more easier to read and compact. Older modules use callbacks whereas, the newer ones work well with promises. This creates makes them difficult to work with each other. Also, the functional modules that use callbacks cannot be used with async/await. One of the ways to use callback functions in such scenarios, is to convert them to promises.

This post is about how to convert callback functions to promises. As an example, let’s consider a function method, that takes a callback as an argument.

It takes 2 numbers, delays for a 10 seconds through the timer, and sends back their sum.

First step is to wrap this callback function within a promise. A promise takes two arguments: resolve and reject.

The task at hand is deferred: call the function ‘resolve’ if the task completes as intended and the ‘reject’ function if the task fails. Wrapping the earlier function within within another function, let’s say ‘promisify’ function:

Notice that the above function, returns another function. The function will be returning a promise, and hence can be used within async/await module. The spread operator is used, which allows an array to be expanded into a list of arguments taken by the function. In block (2), we take the arguments sent to the function and add our own callback to the arguments:

This callback is sent to the method along with the rest of the intended arguments. Then, the method is called:

The spread operator (…arguments) expands the arguments list as:

The above block results in a method that returns a promise. In summary, the code looked like the one below earlier:

After converting into promise, it looks like this:

As you can see, the latter code is much cleaner and easier to read/understand. Also, it is usable with the new async/await keywords.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store