Skip to content
jshacks.dev
Functions

How to Write a Function That Works With Both Callbacks and Promises

Write one JavaScript function that accepts an optional callback and otherwise returns a promise, with error-first rules, no double calls and tests. Node.js 24.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm, TypeScript, Node.js and Vite logos.

Node.js grew up on callbacks, and most of its modules now also offer promises. If you publish a library, you meet both audiences: people who pass (err, result) => {} and people who write await. The old answer was two functions. A cleaner one is a single function that does the work once, calls the callback if the caller passed one and returns a promise if they did not. This post shows that pattern on Node.js 24, the bugs it invites when written carelessly and how to test both paths. It also shows the shorter route, util.promisify, and when it is the better choice. For the callbacks-versus-promises decision itself, see callbacks vs promises vs async/await.

The two conventions

A Node.js-style callback is the last argument, receives an error first and a result second, and is called exactly once. A promise-returning function takes no callback, returns a promise and signals failure by rejecting. The goal is one function that honors both conventions without changing what "success" and "failure" mean.

Start with a callback-only function that reads a user from an in-memory table, with a simulated delay.

JavaScript
const users = new Map([[1, { id: 1, name: "Ada" }]]);

function getUserCallback(id, callback) {
  setTimeout(() => {
    const user = users.get(id);

    if (!user) {
      callback(new Error(`user ${id} not found`));
      return;
    }

    callback(null, user);
  }, 1);
}

getUserCallback(1, (error, user) => console.log(error, user));
getUserCallback(2, (error, user) => console.log(error?.message, user));
Text
null { id: 1, name: 'Ada' }
user 2 not found undefined

The shape is the standard one: on success null then the value, on failure the error and nothing else. Now we make it dual.

One function, both styles

The trick is to write the real work as a promise-returning function and bolt the callback on at the edge.

JavaScript
async function getUserAsync(id) {
  await new Promise((resolve) => setTimeout(resolve, 1));

  const user = users.get(id);

  if (!user) {
    throw new Error(`user ${id} not found`);
  }

  return user;
}

function getUser(id, callback) {
  const promise = getUserAsync(id);

  if (typeof callback !== "function") {
    return promise;
  }

  promise.then(
    (user) => callback(null, user),
    (error) => callback(error),
  );
}

getUser(1, (error, user) => console.log("callback", error, user));

console.log(await getUser(1));
Text
callback null { id: 1, name: 'Ada' }
{ id: 1, name: 'Ada' }

The ordering of the two lines comes from timing: both calls wait one millisecond, and the callback call was started first, so it logs first. The important design is that the core logic exists once, in getUserAsync, and the wrapper only chooses how to deliver the result. Writing the core as a promise function also means errors thrown anywhere inside it become rejections without extra code.

Check the wrapper's two edges. When there is a callback, the function returns undefined, so it does not return a promise that nobody handles. When there is none, the caller gets the promise and handles it.

The trap in .then(success, failure)

The version above uses the two-argument form of then on purpose, and the reason is subtle. Consider the common alternative.

JavaScript
function getUserBuggy(id, callback) {
  getUserAsync(id)
    .then((user) => callback(null, user))
    .catch((error) => callback(error));
}

let calls = 0;

getUserBuggy(1, () => {
  calls += 1;
  if (calls === 1) {
    throw new Error("bug in the caller's callback");
  }
});

await new Promise((resolve) => setTimeout(resolve, 20));

console.log(calls);
Text
2

The user's callback threw an error on its first call. Because the .catch is chained after the .then, it catches that exception too, and calls the callback a second time, with the exception as the error. A callback that should run once ran twice, and it reported the caller's own bug as a failure of the operation. Passing both handlers to a single then fixes it: the second handler handles only rejections of promise, not exceptions thrown by the first handler.

That version still leaves the exception unhandled, which is correct for a callback API. In Node.js an error thrown inside a callback is the caller's bug, and it should surface as an uncaught exception, not be hidden. With .then(a, b), the throw inside a becomes a rejection of the promise returned by then, which no one handles, so Node.js reports an unhandled rejection. That is better than silence, though not identical to the synchronous throw callers of old callback APIs saw. If you want the original behavior, call the callback from process.nextTick or queueMicrotask so that the exception escapes the promise machinery.

JavaScript
promise.then(
  (user) => queueMicrotask(() => callback(null, user)),
  (error) => queueMicrotask(() => callback(error)),
);

queueMicrotask runs the callback after the current handler returns, outside the promise chain, so a throw becomes an uncaught exception as it always did.

Zalgo and consistent timing

A callback API has a second rule: always call back asynchronously, or always synchronously, but never a mixture. A function that calls back synchronously on a cache hit and asynchronously on a miss makes callers write code that behaves differently depending on data, a bug class known as releasing Zalgo.

JavaScript
const cache = new Map();

function fetchBad(key, callback) {
  if (cache.has(key)) {
    callback(null, cache.get(key));
    return;
  }

  setTimeout(() => {
    cache.set(key, key.toUpperCase());
    callback(null, cache.get(key));
  }, 1);
}

const order = [];

fetchBad("a", () => order.push("first call"));
order.push("after first");

await new Promise((resolve) => setTimeout(resolve, 10));

fetchBad("a", () => order.push("second call"));
order.push("after second");

console.log(order);
Text
[ 'after first', 'first call', 'second call', 'after second' ]

On the first call, the callback runs after the code that follows. On the second call, it runs before. Same function, opposite ordering. The promise-based wrapper does not have this problem, because a promise handler always runs asynchronously, even on an already resolved promise. That is a reason to build callback support on top of the promise, as above, and not the other way around.

Rejecting a bad argument

Decide what happens when the caller passes something that is neither a function nor missing. Silently ignoring it hides a mistake, so throw.

JavaScript
function getUserStrict(id, callback) {
  if (callback !== undefined && typeof callback !== "function") {
    throw new TypeError("callback must be a function or omitted");
  }

  const promise = getUserAsync(id);

  if (callback === undefined) return promise;

  promise.then(
    (user) => queueMicrotask(() => callback(null, user)),
    (error) => queueMicrotask(() => callback(error)),
  );
}

try {
  getUserStrict(1, "oops");
} catch (error) {
  console.log(error.name, error.message);
}
Text
TypeError callback must be a function or omitted

Node.js itself does the same in its own APIs: passing a non-function callback throws ERR_INVALID_ARG_TYPE. A synchronous throw is right for a programming error such as this one, and the rejection or the callback error is right for an operational failure such as "user not found".

The shortcut: util.promisify

If you already have a callback function that follows the error-first convention, you do not need to write the wrapper yourself. util.promisify makes a promise version of it. The [Node.js documentation for util.promisify](https://nodejs.org/api/util.html#utilpromisifyoriginal) describes the contract: the function must take a callback as its last argument, in the standard form.

JavaScript
import { promisify } from "node:util";

const getUserPromise = promisify(getUserCallback);

console.log(await getUserPromise(1));

try {
  await getUserPromise(5);
} catch (error) {
  console.log(error.message);
}
Text
{ id: 1, name: 'Ada' }
user 5 not found

Use promisify when you are consuming someone else's callback function, or when you want to keep a callback-first implementation and offer a promise version as a second export. Write the dual function yourself when you are designing a new API and want one name to serve both audiences, or when the function has a result shape that promisify cannot guess, such as a callback with several values after the error. Many Node.js modules take a third route: they ship a separate fs/promises style module, so callers choose by import, and there is no runtime check for a callback at all.

Documenting the dual signature

A function with two modes needs its contract written down, because the editor cannot guess. State plainly in the documentation that the callback is optional, that omitting it returns a promise and that supplying it returns nothing. Mention the error-first order once, near the top, so nobody has to read the implementation to learn it.

For TypeScript users, express the two modes as overloads. One signature takes the callback and returns void, and the other takes no callback and returns Promise<User>. Without the overloads, a caller who awaits the call sees void | Promise<User>, and has to narrow it, which defeats the point of offering both styles. The overloads also make a mistake visible at compile time, such as passing a callback and then awaiting the result.

Testing both paths

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("promise style resolves with the user", async () => {
  assert.deepEqual(await getUser(1), { id: 1, name: "Ada" });
});

test("promise style rejects for a missing user", async () => {
  await assert.rejects(getUser(9), { message: "user 9 not found" });
});

test("callback style gets null then the user", async () => {
  const result = await new Promise((resolve) => {
    getUser(1, (error, user) => resolve({ error, user }));
  });

  assert.deepEqual(result, { error: null, user: { id: 1, name: "Ada" } });
});

test("callback is called exactly once", async () => {
  let calls = 0;

  getUser(1, () => {
    calls += 1;
  });

  await new Promise((resolve) => setTimeout(resolve, 20));
  assert.equal(calls, 1);
});
Text
ℹ tests 4
ℹ pass 4
ℹ fail 0

The last test guards against the double-call bug. It is cheap, and it is the kind of regression that appears only when somebody refactors the wrapper to .then().catch().

Also inAsync
Taggedbeginner
Share

Keep reading

Get new posts by email

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

Unsubscribe in one click. No spam, ever.