How to Use util.promisify in Node.js for Async Functions
In Node.js,
util.promisify converts a function that uses callbacks into one that returns a Promise. This allows you to use modern async/await syntax with older callback-style APIs easily.Syntax
The util.promisify function takes a single argument: the original callback-based function. It returns a new function that returns a Promise.
- Original function: expects a callback as the last argument, usually with the signature
(error, result). - Promisified function: returns a
Promisethat resolves with the result or rejects with the error.
javascript
const { promisify } = require('util'); const promisifiedFunction = promisify(originalFunction);
Example
This example shows how to convert Node.js's fs.readFile (which uses callbacks) into a promise-based function using util.promisify. Then it reads a file asynchronously with async/await.
javascript
const { promisify } = require('util'); const fs = require('fs'); // Convert fs.readFile to return a Promise const readFileAsync = promisify(fs.readFile); async function readMyFile() { try { const data = await readFileAsync('example.txt', 'utf8'); console.log('File contents:', data); } catch (error) { console.error('Error reading file:', error); } } readMyFile();
Output
File contents: (contents of example.txt file)
Common Pitfalls
Common mistakes when using util.promisify include:
- Passing a function that does not follow the Node.js callback style (
(err, result)) will not work correctly. - For functions with multiple callback arguments, only the first result is returned by the promise.
- Not handling errors properly with
try/catchor.catch()when using the promisified function.
javascript
const { promisify } = require('util'); // Wrong: function does not use (err, result) callback function badCallback(arg, callback) { callback(null, arg * 2, 'extra'); // extra argument ignored by promisify } const badPromisified = promisify(badCallback); badPromisified(5).then(result => { console.log('Result:', result); // Only 10, 'extra' is ignored });
Output
Result: 10
Quick Reference
| Term | Description |
|---|---|
| util.promisify(fn) | Converts a callback-based function fn to return a Promise. |
| Original callback | Function expects last argument as callback with (error, result). |
| Promisified function | Returns a Promise that resolves with result or rejects with error. |
| Error handling | Use try/catch or .catch() with promisified functions. |
| Multiple callback results | Only the first result after error is returned by the Promise. |
Key Takeaways
Use
util.promisify to convert callback functions to promise-based ones for easier async code.The original function must follow Node.js callback style with (error, result) arguments.
Promisified functions return a Promise that can be awaited or chained with .then()/.catch().
Only the first callback result is returned; extra callback arguments are ignored.
Always handle errors with try/catch or .catch() when using promisified functions.