Replacing Callbacks with Promises
Replacing callbacks with promises means taking a function that reports its result through a callback and wrapping it so that it returns a Promise instead. You do this when you want to chain steps with .then(), handle every failure in one .catch(), or use async/await with older APIs that were written before promises existed.
Wrapping a callback API by hand
The Promise constructor takes an executor function with two parameters, resolve and reject. Inside it you call the old callback-based function. When its callback fires, you call resolve with the result or reject with the error. This is often called "promisifying" a function.
const fs = require('fs');
function readText(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, text) => {
if (err) {
reject(err);
} else {
resolve(text);
}
});
});
}
readText('config.json')
.then((text) => JSON.parse(text))
.then((config) => console.log('Port:', config.port))
.catch((err) => console.error('Failed:', err.message));
Notice how the error handling moved. Instead of checking err in every nested callback, a single .catch() at the end handles a missing file and invalid JSON alike, because a thrown error inside .then() also rejects the chain.
Turning a timer into a promise
Browser APIs can be wrapped the same way. setTimeout has no error case, so you only need resolve:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function showSteps() {
console.log('Saving...');
await wait(1500);
console.log('Saved!');
}
Once a function returns a promise, it works naturally with await, and the code reads from top to bottom like normal synchronous code.
Let Node do it: util.promisify and the promises API
You rarely need to write wrappers for Node core modules. Two built-in options exist:
util.promisify(fn)converts any function that follows the error-first callback pattern into one that returns a promise.- Many modules ship a promise version already, such as
require('fs/promises')orrequire('timers/promises').
Prefer these over hand-written wrappers for core APIs. Write your own only for third-party code or browser APIs that have no promise version.
Pitfalls when converting
A few mistakes come up again and again:
- Forgetting to return the promise. If your wrapper creates a promise but does not
returnit, callers receiveundefinedand cannot chain on it. - Never settling. If one branch of the callback calls neither
resolvenorreject, the promise stays pending forever and nothing after it runs. - Resolving with an error. Calling
resolve(err)instead ofreject(err)makes a failure look like success, so your.catch()never fires. - Mixing styles. Passing a callback and also using the returned promise leads to the same work being handled twice. Pick one style per function.
Also remember that a promise settles only once. Calling resolve a second time is silently ignored, which protects you from the "callback fired twice" bug.
What you gain
After converting, sequential steps become a flat chain instead of a pyramid, errors travel to one place, and you can combine operations with helpers like Promise.all. The original API still does the real work; the promise is just a cleaner way of receiving its result.
Key point: wrap the callback once, call resolve or reject exactly once inside it, and from then on treat the function like any other promise-returning code.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.