Skip to content
jshacks.dev
Functions

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.

1 min read
Summarize in AI

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.

JavaScript
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);
Text
ENOENT: no such file or directory, open 'missing.txt'
function

The 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.

Also inAsync
Taggednode 24
Share

More snippets

Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read
Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.