Await callback-based library functions
Modernizing legacy APIs
Node.js · Function
Converts an error-first callback-style function into a function that returns Promises. A custom implementation can override the default conversion.
util.promisify() accepts a function whose final argument is an error-first callback and returns a function that produces a Promise. The returned function preserves the original callable interface before the callback, while resolving or rejecting according to the callback's result.
util.promisify(original)| Name | Type | Description |
|---|---|---|
original | Function | A function using an error-first callback as its final argument. |
Function
import { promisify } from 'node:util';
function getValue(callback) {
setTimeout(() => callback(null, 42), 10);
}
const getValueAsync = promisify(getValue);
console.log(await getValueAsync());Converts the error-first callback function into one that can be awaited.
Modernizing legacy APIs
Sequential asynchronous workflows
Special callback signatures
util.promisify() do?It adapts a Node-style callback API to a Promise-based API. The source function must receive an (err, value) => ... callback as its final argument, and the returned function can then be used with Promise APIs such as await.
Follow-up: What happens when the source function has a custom implementation? If original[util.promisify.custom] exists, promisify() returns that value instead.
original parameter represent?The argument is the callback-based function to adapt. Its documented type is Function, and the callback is expected to be the final argument.
Follow-up: What if the value is not callable? promisify() throws an error when original is not a function.
The function returns another Function. Calling that converted function produces a Promise whose outcome follows the callback's error-first result.
Follow-up: Can any callback function be converted reliably? No; a function whose final argument is not an error-first callback can receive an incompatible callback and behave incorrectly.
util.promisify.customutil.callbackify