# How to Change Callbacks to Promises in JavaScript

## Introduction

Handling asynchronous operations with **callbacks can be tedious**, while handling them with **promises is more efficient**. However, managing asynchronous operations with `async`**/**`await` **is exceptionally effective.**

In this article, **we will learn how to convert traditional callbacks to promises**.

### Prerequisite

* Understanding how to use callback functions.
    
* Understanding how to use promises in JavaScript.
    

## Why use promises instead of callbacks?

The callback has many limitations:

* Managing asynchronous requests
    
* Poor code readability
    
* Difficult error handling
    

To address these issues, we should use promises. To learn how promises work, check out my article [**click here**](https://blog.fraddyoliveira.com/promises-in-javascript-c9764cba4a23).

## Why convert callbacks to promises?

Promises were introduced in Javascript in ES6 (also know as ECMAScript 2015).

Before ES6, only callbacks could handle asynchronous operations. Many libraries or applications written before ES6 use callbacks. These codebases may still use callbacks because they are not actively maintained or upgrading them requires significant effort.

We will learn how to convert callbacks to promises using the **NodeJs module** and also write a **generic function for this purpose**.

## Methods to convert callbacks to promises:

### **1) Basic approach**

With this approach, we will get a **basic understanding of how to convert a callback to a promise**. Let’s learn through an example.

Consider an example based on the **browser** `onload` **event**:

%[https://gist.github.com/fraddy-oliveira/f9a71e4f5b2749008d97b5f260b314f5] 

**Let’s analyze** the example:

* The `onLoad` function returns a promise.
    
* In the executor function, the resolution function `resolve` is assigned to `window.onload`.
    
* Here, `window.onload` and `resolve` refer to the same function.
    
* When the `load` event triggers, the resolution function will execute.
    
* Now, the `then` callback will execute. The `then` callback should contain the code that runs after the browser loads.
    

### **2) Util library**

This approach is specific to the Node environment. The `util` library is stable and built into Node, providing a method to convert callbacks to promises.

Consider an example based on the `readFile` method of the NodeJs `fs` module.

**Example Prerequisite:**

* Create a data file to be read, located in the same directory as the executable file.
    
* Name the data file `student_marks.txt`.
    

%[https://gist.github.com/fraddy-oliveira/f3633fa7ce0f8adbc2c1cd8fa3e45437] 

**Let’s analyze** the example:

* The method `fs.readFile` is asynchronous and accepts a callback as the last parameter.
    
* The `callback` format requires two parameters: the first is an `error` parameter, and the second is the data returned by the method.
    
* Using `util.promisify(fs.readFile)`, a new function is created from the `fs.readFile` method. This new function returns a promise.
    
* In the example above, the `readFileAsync` function returns a promise.
    

**Things to note** about `util.promisify`:

* The function to be converted must accept a **callback function as the last parameter**.
    
* The callback function should **accept only two parameters**.
    
* The first parameter of the callback must be an `error` object, and the second parameter should be the `return` value of the function.
    

### **3) Generic approach**

In some scenarios, the callback can accept more than two parameters. For example, the first is the error parameter, and the second and third can be results. In that case, the `util.promisify` library cannot be used. As a workaround, we will use a function named `promisify`.

`promisify` is a custom function that is well-tested and supports error handling. It converts callbacks to promises and can be used in both Node.js and browsers.

%[https://gist.github.com/fraddy-oliveira/bb75671a1566171a20421e4f3fccb82d] 

**Let’s analyze** `promisify`:

* Accepts 2 arguments.
    
* The first argument, `func`, must be a callback-based function.
    
* The second argument is `thisArg`, which is the execution context of `func`. The default value is `null`.
    
* The return value of `promisify` is a function that, when called, returns a `Promise`.
    
* Check the example below for the usage of `promisify`.
    

%[https://gist.github.com/fraddy-oliveira/36386a2c08c9497f21e94a6bad3ddd13] 

Below is another example which `promisify` Node.js `fs.readFile` function.

%[https://gist.github.com/fraddy-oliveira/560151b6644e0c6dc6502fe2348476df] 

## Conclusion

In addition to the methods discussed in this article, there are alternative approaches, such as utilizing **third-party libraries**. One notable library is [Bluebird JS](http://bluebirdjs.com/).

Thank you for reading. Your feedback on the content of this article is appreciated.
