What does util.promisify do and when is it useful?
It converts a function that takes an error-first callback as its last argument into one that returns a promise, so older callback APIs can be used with async/await.
Explain it simply
Many older Node APIs follow one convention: the last argument is a callback (err, result) => {}. Promises and await are easier to compose, but you cannot await a callback. util.promisify is an adapter, like a travel plug converter: your new device works with the old socket.
Example
const { promisify } = require("util");
const fs = require("fs");
const readFile = promisify(fs.readFile);
async function main() {
try {
const text = await readFile("marks.txt", "utf8");
console.log(text.length);
} catch (err) {
console.log("could not read:", err.code);
}
}
main();The wrapper resolves with the second callback argument and rejects with the first if it is not null.
Notes:
- It only works for callbacks following the
(err, value)convention. - Many core modules now have promise versions ready to use, such as
require("fs/promises")andrequire("timers/promises"), so you often do not needpromisify. - Functions that lose
thismust be bound:promisify(obj.method.bind(obj)).
What to say in the interview
"promisify wraps error-first callback functions so they return promises. I use it for legacy APIs, but for built-in modules I prefer the native promise versions like fs/promises."
Common mistakes
- Promisifying a function whose callback does not follow the error-first convention.
- Losing
thiswhen passing a class method.