Skip to content
jshacks.dev
Async

Structured Concurrency in JavaScript Without a Library

Learn what structured concurrency means, why Promise.all leaves orphaned tasks and how AbortController, Promise.allSettled and a small scope helper fix it.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Redis and RabbitMQ logos.

Structured concurrency is a rule about lifetimes: a task started inside a block of code must finish, or be cancelled, before the block exits. If you start three requests in a function, the function does not return until all three are done or stopped. JavaScript does not enforce that rule, and its default tools break it in one specific, common way. Promise.all rejects as soon as one promise rejects, and the other promises keep running, unobserved, doing work nobody will read. This post explains the idea, shows the orphan problem with exact output, builds the guarantee from AbortController and Promise.allSettled, and writes a small scope helper that makes the pattern reusable.

The problem: Promise.all abandons its siblings

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

async function task(name, ms, fail = false) {
  await sleep(ms);
  console.log(`${name} finished`);
  if (fail) throw new Error(`${name} failed`);
  return name;
}

try {
  await Promise.all([task("a", 10, true), task("b", 40), task("c", 60)]);
} catch (error) {
  console.log("caught:", error.message);
}

console.log("function returned");
await sleep(100);
Text
a finished
caught: a failed
function returned
b finished
c finished

Promise.all rejected at 10 ms, and the catch ran. But b and c kept running and finished after the function had already returned. If those tasks write to a database or hold a socket, the caller sees an error while work is still in flight, and what finishes later can collide with a retry. Nobody owns those tasks any more, which is the definition of an orphan.

The rule we want

  1. A function that starts concurrent work does not return until all of it has settled.

  2. When one task fails, the siblings are cancelled, not abandoned.

  3. Cancellation is cooperative: tasks must watch a signal and stop.

JavaScript gives us the pieces: AbortController for cancellation and Promise.allSettled to wait for everything, even after a failure.

Step 1: pass a signal into every task

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

async function task(name, ms, signal, fail = false) {
  await sleep(ms, undefined, { signal });
  console.log(`${name} finished`);
  if (fail) throw new Error(`${name} failed`);
  return name;
}

The sleep rejects with an AbortError when the signal aborts, so the task stops waiting. Real tasks pass the same signal to fetch, database drivers or child processes.

Step 2: abort on first failure, then wait for everyone

JavaScript
async function all(makeTasks) {
  const controller = new AbortController();
  const tasks = makeTasks(controller.signal).map((promise) =>
    promise.catch((error) => {
      controller.abort();
      throw error;
    })
  );

  const results = await Promise.allSettled(tasks);

  const firstFailure = results.find(
    (r) => r.status === "rejected" && r.reason.name !== "AbortError"
  );
  if (firstFailure) throw firstFailure.reason;
  return results.map((r) => r.value);
}

try {
  await all((signal) => [
    task("a", 10, signal, true),
    task("b", 40, signal),
    task("c", 60, signal),
  ]);
} catch (error) {
  console.log("caught:", error.message);
}

console.log("function returned");
Text
a finished
caught: a failed
function returned

The failure of a aborted the signal, so the sleeps in b and c rejected with AbortError and never reached their log lines. Promise.allSettled waited for all three to settle before all returned, so nothing is running when the caller continues. The function picks the first non-abort failure as the reason, because the abort errors of the siblings are a consequence, not the cause.

Step 3: a scope that owns its tasks

Wrapping the pattern in a small helper keeps call sites short. A scope collects the tasks you start and waits for them on exit.

JavaScript
async function withScope(body) {
  const controller = new AbortController();
  const tasks = [];

  const scope = {
    signal: controller.signal,
    spawn(fn) {
      const promise = fn(controller.signal).catch((error) => {
        controller.abort();
        throw error;
      });
      tasks.push(promise);
      return promise;
    },
  };

  let bodyError;
  let result;
  try {
    result = await body(scope);
  } catch (error) {
    bodyError = error;
    controller.abort();
  }

  const settled = await Promise.allSettled(tasks);
  const failure =
    bodyError ??
    settled.find((r) => r.status === "rejected" && r.reason.name !== "AbortError")
      ?.reason;

  if (failure) throw failure;
  return result;
}

Usage reads like a block with a lifetime:

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

const result = await withScope(async (scope) => {
  const a = scope.spawn(async (signal) => {
    await sleep(10, undefined, { signal });
    return "a";
  });
  const b = scope.spawn(async (signal) => {
    await sleep(20, undefined, { signal });
    return "b";
  });
  return [await a, await b];
});

console.log(result);
Text
[ 'a', 'b' ]

If the body throws, or any spawned task fails, the signal aborts, every other task is asked to stop and withScope waits for all of them before it rejects. Control never leaves the block while tasks are still running, which is the guarantee.

A built-in alternative: AbortSignal.any

When several things should cancel one operation, AbortSignal.any combines signals. A task can listen to the scope's signal and to its own timeout at once.

JavaScript
const scopeController = new AbortController();

const combined = AbortSignal.any([
  scopeController.signal,
  AbortSignal.timeout(50),
]);

combined.addEventListener("abort", () => {
  console.log("aborted because:", combined.reason.name);
});

setTimeout(() => scopeController.abort(), 10);
Text
aborted because: AbortError

The scope aborted first at 10 ms. Without the manual abort, the reason would be TimeoutError at 50 ms. Both AbortSignal.any and AbortSignal.timeout are available in Node.js 20 and later and in current browsers.

What JavaScript cannot give you

The helpers above rely on every task cooperating. A task that ignores its signal keeps running, and Promise.allSettled then waits for it, which delays the function's return. That is the correct behavior for the guarantee, and a surprise when one rogue task has no timeout. In languages with built-in structured concurrency, such as Kotlin's coroutine scopes or Swift's task groups, the runtime can cancel at suspension points automatically. JavaScript has no way to cancel a running await; it can only ask. Some proposals and libraries add scopes, such as Effection, and the pattern above covers most needs with no dependency.

Where it matters most

  • Request handlers. A handler that fans out to three services must not leave calls running after it has sent the response.

  • Tests. Orphaned tasks from one test write logs, touch files and hold sockets during the next. A scope that waits makes tests deterministic.

  • Shutdown. SIGTERM handlers should abort a root scope and wait for it, which gives a clean exit.

Common mistakes

**Using Promise.all and believing the siblings stopped.** They continue.

Aborting without waiting. Abort is a request. Wait with allSettled for the tasks to acknowledge it.

Dropping the first error. After an abort, siblings reject with AbortError. Report the real cause, not the echo.

Tasks that ignore the signal. Pass it to every API that accepts one.

Applying it to a request handler

Consider a handler that must call a user service, an orders service and a recommendations service, and render a page from all three. Without a scope, the handler uses Promise.all, and when the user service fails, the other two calls continue in the background. The handler returns an error page, and the two calls complete later, hold connections from the pool and write cache entries for a request that no longer exists. Under load, those orphaned calls add up, and the pool fills with work whose results nobody reads.

With a scope, the handler passes the scope's signal to each client call, and the failure of the user service aborts the signal. The other two calls are cancelled at the network layer, where the client library supports signals, and the connections return to the pool at once. The handler returns only after all three have settled, so the connection count at the end of every request is known, which makes capacity planning something you can reason about.

Timeouts as part of the scope

A scope is also the natural place for a deadline. Combine the scope's own signal with AbortSignal.timeout(ms) using AbortSignal.any, and give the combined signal to every task. Now the whole operation has one budget: whichever tasks are still running when it expires are cancelled together, and the scope rejects with the timeout reason. That is easier to reason about than a separate timeout on each call, where the total time is the sum of whatever each was willing to wait.

What about tasks that cannot be cancelled

Some operations cannot take a signal: a library call that never exposes one, a synchronous computation or a write that has already been sent. The scope can still wait for them, which keeps the guarantee that nothing outlives the block, and it cannot hurry them up. For such tasks, wrap the call so that the scope stops waiting when it is cancelled, by racing it against the signal, and be explicit in a comment that the underlying work continues. This trades the guarantee for responsiveness, and it is a decision that belongs in the code, not in an assumption.

Testing a scope

Write tests that cover the three outcomes: all tasks succeed, one fails and the others are cancelled, and the body throws while tasks are running. In each, assert that no task is still running when the scope returns, which you can do by counting started and finished tasks in the test. A test that verifies the guarantee is worth more than any number of tests that verify the happy path, since the guarantee is the reason the helper exists.

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
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

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.