Transitioning to Promises from Error-First
You'll learn how util.promisify automatically converts error-first callback functions into promise-returning functions, making async code cleaner and more consistent.
The Bridge Between Two Worlds
Error-first callbacks and Promises solve the same problem—handling asynchronous operations—but with very different patterns. Manually converting between them is tedious: you'd need to wrap every callback in a new Promise constructor, check for errors, and call resolve or reject accordingly.
Node.js provides util.promisify to automate this conversion. It takes any function that follows the error-first callback convention (where the last parameter is a callback receiving (err, result)) and returns a new function that returns a Promise instead.
How It Works
const util = require('util');
const fs = require('fs');
// Old way: error-first callback
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error:', err);
return;
}
console.log('Data:', data);
});
// Convert to promise-returning function
const readFilePromise = util.promisify(fs.readFile);
// New way: promise-based
readFilePromise('data.txt', 'utf8')
.then(data => console.log('Data:', data))
.catch(err => console.error('Error:', err));
util.promisify creates a wrapper that:
- Calls the original function with your arguments plus a special callback
- Returns a Promise immediately
- Resolves the Promise if the callback receives
nullorundefinedas the error - Rejects the Promise if the callback receives an error
Key Takeaway: util.promisify converts error-first callback functions into promise-returning ones automatically, letting you transition from callback-based to promise-based code without manual wrapping.