Convert a callback function to a promise
Convert a callback function to a promise in JavaScript with new Promise, and see how util.promisify does the same for Node.js style callbacks.
Older Node.js APIs take a callback with the error first. Wrapping one in a Promise lets you use await and try/catch with it.
import { readFile } from 'node:fs';
import { promisify } from 'node:util';
const readFileAsync = (path, encoding) =>
new Promise((resolve, reject) => {
readFile(path, encoding, (error, data) => (error ? reject(error) : resolve(data)));
});
try {
await readFileAsync('missing.txt', 'utf8');
} catch (error) {
console.log(error.message);
}
const readFilePromise = promisify(readFile);
console.log(typeof readFilePromise);ENOENT: no such file or directory, open 'missing.txt'
functionThe wrapper settles the promise from inside the callback: reject with the error if there is one, otherwise resolve with the data. util.promisify does this for any function that takes an error-first callback as its last argument.
Those two only fit that convention. A callback that is called several times, such as an event listener, cannot become one promise. Many modules also ship promise versions, for example node:fs/promises, so check for one before wrapping.