Wrapping callbacks into promises

How we can reuse old APIs that are using callbacks to use promises.

Let’s say we have a module which works really nice but it’s exposing functions that are using callbacks instead promises.
Our module has a function named fetch, we usually use it as follow:

1
2
3
4
5
6
7
8
const { fetch } = require('some-module');
fetch((error,data) => {
if(error) {
// Do something with the error
} else {
// Do something with the data
}
})

We can build a wrapper as follow:

1
2
3
4
5
6
7
8
9
10
11
12
const { fetch } = require('some-module');
const fetchPromise = () => {
return new Promise((resolve,reject) => {
fetch((error,data) => {
if(error) {
reject(error);
} else {
resolve(data);
}
})
})
}

Now, we have our fetchPromise method ready to be used as follow:

1
2
3
4
5
6
7
fetchPromise()
.then(data => {
// Do something with the data
})
.catch(error => {
// Do something with the error
})

Even better is to use it with async/await:

1
2
3
4
5
6
7
// Inside an async function
try {
const data = await fetchPromise();
// Do something with the data
} catch (error) {
// Do something with the error or just return Promise.reject(error);
}

Hope it helps, happy coding!