TypeScript

Promisify a Callback Function

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Convert a Node-style `(err, result)` callback API into a Promise-returning function. Type-safe via generics — the inferred Promise resolves to the original callback's result type.
TypeScript
Raw
type NodeCallback<T> = (err: Error | null, result?: T) => void;

export function promisify<Args extends unknown[], T>(
  fn: (...args: [...Args, NodeCallback<T>]) => void,
): (...args: Args) => Promise<T> {
  return (...args) =>
    new Promise<T>((resolve, reject) => {
      fn(...args, (err, result) => {
        if (err) reject(err);
        else     resolve(result as T);
      });
    });
}

// Example: fs.readFile (callback) → promise
import * as fs from 'node:fs';
const readFileP = promisify<[string, string], string>(fs.readFile);
const text = await readFileP('package.json', 'utf8');
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.