0
0
JavascriptHow-ToBeginner · 2 min read

JavaScript How to Convert Callback to Promise Easily

Wrap the callback function inside a new Promise by calling resolve on success and reject on error, like new Promise((resolve, reject) => { callbackFunc((err, result) => { if (err) reject(err); else resolve(result); }); }).
📋

Examples

InputcallbackFunc((err, data) => { if (err) console.error(err); else console.log(data); })
OutputPromise that resolves with data or rejects with error
InputreadFile('file.txt', callback)
OutputPromise that resolves with file content or rejects with error
InputcallbackFunc(null, 'Success!')
OutputPromise resolves with 'Success!'
🧠

How to Think About It

To convert a callback to a promise, think of wrapping the callback call inside a new Promise. The Promise constructor takes two functions: resolve and reject. Inside the callback, call reject if there is an error, otherwise call resolve with the result. This way, the callback style becomes a promise that can be awaited or chained.
📐

Algorithm

1
Create a new Promise object.
2
Inside the Promise, call the original callback function.
3
In the callback, check if there is an error.
4
If error exists, call reject with the error.
5
If no error, call resolve with the result.
6
Return the Promise.
💻

Code

javascript
function callbackToPromise(callbackFunc) {
  return new Promise((resolve, reject) => {
    callbackFunc((err, result) => {
      if (err) reject(err);
      else resolve(result);
    });
  });
}

// Example callback function
function exampleCallback(cb) {
  setTimeout(() => cb(null, 'Done!'), 1000);
}

callbackToPromise(exampleCallback).then(console.log).catch(console.error);
Output
Done!
🔍

Dry Run

Let's trace exampleCallback through callbackToPromise

1

Call callbackToPromise

callbackToPromise(exampleCallback) creates a new Promise

2

Inside Promise, call exampleCallback

exampleCallback runs and waits 1 second

3

Callback fires with (null, 'Done!')

No error, so resolve('Done!') is called

StepCallback ArgumentsPromise Action
1N/APromise created
2N/AexampleCallback called
3(null, 'Done!')resolve('Done!')
💡

Why This Works

Step 1: Wrap callback in Promise

The Promise constructor lets you run asynchronous code and decide when to finish with resolve or reject.

Step 2: Handle callback results

Inside the callback, check if err exists. If yes, call reject(err) to signal failure.

Step 3: Resolve on success

If no error, call resolve(result) to pass the successful result to the Promise.

🔄

Alternative Approaches

Using util.promisify (Node.js)
javascript
const { promisify } = require('util');
const fs = require('fs');
const readFilePromise = promisify(fs.readFile);
readFilePromise('file.txt', 'utf8').then(console.log).catch(console.error);
This is a built-in Node.js method to convert callback functions to promises automatically, but only works for Node-style callbacks.
Manual Promise wrapper with parameters
javascript
const fs = require('fs');
function readFilePromise(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf8', (err, data) => {
      if (err) reject(err);
      else resolve(data);
    });
  });
}
readFilePromise('file.txt').then(console.log).catch(console.error);
This approach manually wraps a callback function with parameters into a Promise.

Complexity: O(1) time, O(1) space

Time Complexity

Wrapping a callback in a Promise adds no loops or extra time complexity; it simply wraps the existing asynchronous call.

Space Complexity

The Promise wrapper uses constant extra space for the Promise object and callback closure.

Which Approach is Fastest?

Using util.promisify is efficient and clean for Node.js callbacks, while manual wrapping is flexible but slightly more verbose.

ApproachTimeSpaceBest For
Manual Promise WrapperO(1)O(1)Any callback function
util.promisify (Node.js)O(1)O(1)Node.js style callbacks
Legacy callback usageO(1)O(1)Older code, no Promise support
💡
Always call reject on errors and resolve on success inside the callback to properly convert it to a Promise.
⚠️
Forgetting to handle the error case and only calling resolve causes the Promise to never reject on failure.