How to Wait for Multiple Events in JavaScript
Wait for multiple events in JavaScript with promises: all of them, any of them, with a timeout, and with cleanup so listeners never leak.

Sometimes code must pause until several things have happened: a page has loaded and the user has granted a permission, a socket has opened and the first message has arrived, two child processes have both reported ready. Each of those things is an event, and events do not return promises. To wait for multiple events you first turn each event into a promise, then combine the promises with the tool that matches the question you are asking: all of them, the first of them, or all of them within a time limit. This post builds that from small pieces, using Node.js 24 and current browsers, with output for each case. The conversion step is the same one covered in turning a callback API into a promise, applied to events instead.
Turn one event into a promise
An event listener fires zero or more times, while a promise settles once, so the helper listens for the first occurrence and removes itself. The once option on addEventListener handles the removal in browsers and in Node.js, where EventTarget is a global.
export function once(target, name) {
return new Promise((resolve) => {
target.addEventListener(name, resolve, { once: true });
});
}
const target = new EventTarget();
setTimeout(() => target.dispatchEvent(new Event("ready")), 10);
const event = await once(target, "ready");
console.log(event.type);readyFor Node.js EventEmitter, the standard library already has this: events.once(emitter, name) returns a promise that resolves with an array of the event's arguments. It also rejects if the emitter emits error while waiting, which is behavior worth keeping in your own helper if you work with emitters.
import { EventEmitter, once } from "node:events";
const emitter = new EventEmitter();
setTimeout(() => emitter.emit("ready", "db", 5432), 10);
const [service, port] = await once(emitter, "ready");
console.log(service, port);db 5432Wait for all events with Promise.all
When every event must happen before you continue, pass the promises to Promise.all. The order the events fire in does not matter, and the result array follows the order you listed them.
import { EventEmitter, once } from "node:events";
const database = new EventEmitter();
const cache = new EventEmitter();
setTimeout(() => cache.emit("ready", "cache"), 30);
setTimeout(() => database.emit("ready", "database"), 10);
const [[db], [ca]] = await Promise.all([
once(database, "ready"),
once(cache, "ready"),
]);
console.log(db, ca);database cacheThe cache event fired second but sits second in the result because the array follows the order of the inputs, not the order of arrival. One important detail: both listeners must be attached before either event can fire. Creating the promises in the same expression, as above, guarantees that. If you await the first and only then create the second, an event that fires in between is lost, and the program waits forever.
Wait for the first event with Promise.race
Use Promise.race when any one event is enough, for example a connection that succeeds or a user who cancels. The race settles with whichever promise settles first.
import { EventEmitter, once } from "node:events";
const socket = new EventEmitter();
setTimeout(() => socket.emit("open"), 20);
setTimeout(() => socket.emit("close"), 50);
const winner = await Promise.race([
once(socket, "open").then(() => "open"),
once(socket, "close").then(() => "close"),
]);
console.log(winner);openThe losing promise is not canceled, and its listener stays attached until its event fires or the emitter is discarded. In a long-lived process that matters, so the next sections show how to clean up.
Add a timeout
Waiting without a limit is a bug waiting for a bad day. If the event never fires, the program hangs with no message. AbortSignal.timeout() produces a signal that aborts after a delay, and events.once accepts a signal option and rejects with an AbortError when it fires. The option is available in Node.js 15 and later.
import { EventEmitter, once } from "node:events";
const emitter = new EventEmitter();
try {
await once(emitter, "ready", { signal: AbortSignal.timeout(50) });
} catch (error) {
console.log(error.name);
}TimeoutErrorAbortSignal.timeout rejects with a TimeoutError, not an AbortError, which makes the cause easy to tell apart from a manual abort. In events.once the listener is removed when the signal fires, so no stale handler remains. For the browser, addEventListener also accepts a signal in its options, which removes the listener when the signal aborts.
Collect several occurrences of one event
Sometimes the question is not "which events" but "how many times", such as waiting for three messages. A promise cannot do that on its own, because it settles once. Count inside a listener and resolve when the count is reached.
import { EventEmitter } from "node:events";
function waitForCount(emitter, name, count) {
return new Promise((resolve) => {
const received = [];
const handler = (value) => {
received.push(value);
if (received.length === count) {
emitter.off(name, handler);
resolve(received);
}
};
emitter.on(name, handler);
});
}
const emitter = new EventEmitter();
const pending = waitForCount(emitter, "message", 3);
["a", "b", "c", "d"].forEach((m, i) => setTimeout(() => emitter.emit("message", m), i * 5));
console.log(await pending);[ 'a', 'b', 'c' ]The fourth message arrives after the handler has removed itself, so it is ignored. Removing the listener at completion is the habit that keeps a counted wait from leaking.
Keep going when some events fail
Promise.all rejects as soon as any input rejects. When you want to know the outcome of every wait, including failures, use Promise.allSettled, which always resolves with a status per input.
const results = await Promise.allSettled([
Promise.resolve("a"),
Promise.reject(new Error("b failed")),
]);
console.log(results.map((r) => r.status));[ 'fulfilled', 'rejected' ]This fits startup checks, where the program should report every service that failed to come up rather than stopping at the first.
A few mistakes to avoid
Attaching listeners too late. The event can fire before the listener exists. Create all waiting promises first, then trigger the work that causes the events.
Waiting on an event that already happened. Events are not remembered. If a socket is already open, waiting for open never resolves. Check the current state first, such as readyState on a WebSocket, and wait only if the state is not final.
Ignoring the error event. An emitter that emits error with no listener throws and can crash the process. events.once listens for error automatically while it waits, which is another reason to prefer it over a hand-written helper.
Leaking listeners in loops. Creating a new race against the same emitter in every iteration adds a new losing listener each time. Node.js warns after more than ten listeners on one event. Use an AbortController per wait and abort it once the winner is known.
Choosing between the combinators
The three combinators answer different questions, and picking by name rather than by question is the usual source of bugs. Ask what must be true before the program continues. If every event is a precondition, such as a database and a cache both reporting ready, the answer is Promise.all. If any one event is enough, such as a connection opening or a user pressing cancel, it is Promise.race. If the program should continue regardless and report what happened, it is Promise.allSettled. There is also Promise.any, which resolves with the first fulfilled promise and ignores rejections until all of them have failed, which suits "try three mirrors and use whichever answers".
A second question is what should happen to the events you stopped waiting for. With all, a rejection leaves the other promises running, and their listeners remain until their events fire. With race, the losers keep their listeners as well. In a script that exits after the wait this does not matter. In a server that waits on every incoming connection it adds up, so give each wait an AbortController, pass its signal to every once call and abort it in a finally block. That makes the cleanup a property of the wait, not something each event source has to remember.
Testing a wait
A wait is easy to test because the events are under your control. Create the emitter in the test, start the wait without awaiting it, emit the events in a chosen order, then await the result. Test the unhappy paths too: emit an error and assert the promise rejects, and let the timeout expire using AbortSignal.timeout with a very small delay. The case most worth covering is the one where the event fires before the listener is attached, because that is the one that hangs in production and looks like a network problem.


