Skip to content
jshacks.dev
Async

Callbacks vs Events vs Promises for Library APIs

Choose between callbacks, event emitters and promises when designing a JavaScript library API, with examples of one-shot results, events and error handling.

7 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, npm, Vite and TypeScript logos.

When you publish a library, the shape of its asynchronous API becomes a promise you keep for years. Callers write code against it, wrap it, mock it and complain about it. Three shapes dominate in JavaScript: a callback you pass in, an event emitter you subscribe to, and a promise you await. They are not interchangeable. A callback or a promise models something that happens once, an event emitter models something that can happen many times, and each has a different story for errors, cancellation and composition. This post compares callbacks vs events vs promises for library APIs, using Node.js 24 examples, and gives a decision rule. It also covers the dual API, where one function supports both a callback and a promise, and why you should probably avoid writing it today.

One result: callback or promise

Suppose a function reads a configuration and gives back an object. With a Node.js-style callback, the last argument is a function and its first parameter is an error.

callback-api.mjsJavaScript
function loadConfig(name, callback) {
  setTimeout(() => {
    if (name === "missing") return callback(new Error("config not found"));
    callback(null, { name, retries: 3 });
  }, 10);
}

loadConfig("app", (error, config) => {
  console.log(error, config);
});
loadConfig("missing", (error, config) => {
  console.log(error.message, config);
});
Text
null { name: 'app', retries: 3 }
config not found undefined

The same function returning a promise:

promise-api.mjsJavaScript
function loadConfig(name) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (name === "missing") return reject(new Error("config not found"));
      resolve({ name, retries: 3 });
    }, 10);
  });
}

console.log(await loadConfig("app"));
try {
  await loadConfig("missing");
} catch (error) {
  console.log(error.message);
}
Text
{ name: 'app', retries: 3 }
config not found

For a single result, the promise wins on almost every count. It composes with Promise.all, works with await and try/catch, cannot be called twice, and cannot silently swallow an error, since an unhandled rejection is reported. The callback version has a problem the promise version cannot have: nothing stops the library from calling the callback twice, or both synchronously and asynchronously depending on a code path, a bug known as releasing Zalgo. A promise handler always runs asynchronously, so callers never see that.

Many results: events

Some things happen repeatedly: a server receives requests, a file produces chunks, a socket emits messages. A promise cannot model that because it settles once. An event emitter fits.

events-api.mjsJavaScript
import { EventEmitter } from "node:events";

class Ticker extends EventEmitter {
  start(count) {
    let n = 0;
    const id = setInterval(() => {
      this.emit("tick", ++n);
      if (n === count) {
        clearInterval(id);
        this.emit("done");
      }
    }, 10);
    return this;
  }
}

new Ticker()
  .on("tick", (n) => console.log("tick", n))
  .on("done", () => console.log("done"))
  .start(3);
Text
tick 1
tick 2
tick 3
done

Events have a weakness that surprises people: an error event with no listener throws and can crash the process. Node.js treats emit("error", err) specially, so a library that emits errors must document that callers need to attach an error listener. An unobserved event is also lost: if the library emits ready before the caller attached a listener, the caller never learns of it. For one-shot facts, give the caller a promise instead, or let them await the next occurrence with events.once(emitter, "ready").

Combining the shapes

A good library API often uses two shapes together, each for what it models. An object that represents a long-running operation can return a promise for the final result and also emit events for progress.

combined.mjsJavaScript
import { EventEmitter } from "node:events";

function download(url) {
  const progress = new EventEmitter();
  const done = new Promise((resolve) => {
    let percent = 0;
    const id = setInterval(() => {
      percent += 50;
      progress.emit("progress", percent);
      if (percent === 100) {
        clearInterval(id);
        resolve(`downloaded ${url}`);
      }
    }, 10);
  });
  return { progress, done };
}

const job = download("/file.zip");
job.progress.on("progress", (p) => console.log(`${p}%`));
console.log(await job.done);
Text
50%
100%
downloaded /file.zip

Progress is a stream of facts, so it is an event. Completion is a single outcome, so it is a promise. This split keeps each part simple, and callers who do not care about progress can ignore the emitter and just await job.done.

Streams of values: async iterators

When the repeated thing is a sequence a caller wants to consume at their own pace, a third option is better than events: return an async iterable. The caller writes for await, gets backpressure and a clean place to put try/catch, and cancels by breaking out of the loop. For libraries that produce many values, such as paginated results, this is often the most pleasant shape. The comparison between push and pull models appears in RxJS vs async iterators.

Error handling compared

ShapeHow errors arriveCommon mistake
CallbackFirst argument, by conventionForgetting to check it, or calling the callback twice
PromiseRejectionNot awaiting, so the rejection is unhandled
Event emittererror eventNo error listener, so the process throws
Async iteratorException from the loopNot wrapping the loop in try

Promises and iterators put errors in the language's normal control flow, which is why they are easier to get right. Callbacks and emitters rely on conventions that callers have to remember.

Cancellation

None of the three has built-in cancellation. The modern convention is to accept an AbortSignal in an options object, as fetch, fs.readFile and events.once do. A library function that returns a promise should take { signal } and reject with the signal's reason when it aborts. This works the same for promises and for async iterators, and it avoids inventing a custom cancel() method that every library names differently.

signal-api.mjsJavaScript
function wait(ms, { signal } = {}) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);
    const id = setTimeout(resolve, ms, "waited");
    signal?.addEventListener("abort", () => {
      clearTimeout(id);
      reject(signal.reason);
    });
  });
}

const controller = new AbortController();
setTimeout(() => controller.abort(new Error("stopped by caller")), 20);
try {
  await wait(1000, { signal: controller.signal });
} catch (error) {
  console.log(error.message);
}
Text
stopped by caller

The dual API trap

Older Node.js libraries accept an optional callback and return a promise if none is given. It seems friendly, but it makes the function harder to document, to type and to test, and it invites the double-delivery bug. Node.js itself moved to separate entry points instead: fs.readFile takes a callback, while fs/promises has the promise version. If you must support both, publish two modules or two named functions, and let util.promisify serve callers who have an old callback function and want a promise.

Making a choice

Decide by what the thing is. If it produces one result or one failure, return a promise. If it produces a sequence the caller will consume, return an async iterable. If it announces things that may happen at any time and nobody needs to wait for them, such as a server's connections, use an event emitter. Reserve callbacks for hot paths where allocating a promise matters, and for APIs that call back many times with a tight contract, such as an array method's map. Always document whether callbacks are invoked synchronously or asynchronously, and keep it consistent.

Where the advice stops

Do not rewrite a stable callback API in a library with many users overnight. Add the promise version alongside, deprecate gradually and keep the old behavior until a major version. And remember that an event emitter is not wrong for a single result when the object is long-lived and the event is its way of reporting state changes. The rule is about fit, not fashion.

Documenting the contract

Whatever shape you choose, write down the contract in the API reference, because the shape alone does not say everything. For a promise, state what it resolves with and which error types it can reject with, and whether it can reject for reasons other than the ones listed. For an event emitter, list every event name, the arguments each one carries and whether error is emitted. For an iterator, state what happens when the caller stops early and whether resources are released. Callers read these notes when something goes wrong in production, and a missing line in the documentation becomes a support question.

Type definitions are part of the contract too. In TypeScript, a typed EventEmitter or a function overload that returns Promise<Config> catches misuse before it ships. Libraries that ship their own .d.ts files make the intended shape obvious to every editor, and a mismatch between the types and the behavior is a bug in the library, not in the caller.

Also inAPIs
Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

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