WaitGroup Tracks Parallel Task Completion

Count in-flight tasks with a WaitGroup: add before spawning, done in each task, and await wait() so the program resumes exactly when all work drained.

TypescriptResilience

Code

typescriptsnippet
49 lines
// WaitGroup: track task completion with a counter; wait() resolves
// once the counter drains to zero
class WaitGroup {
  private count = 0;
  private gate = Promise.withResolvers<void>();
  private released = false;

  add(delta: number): void {
    if (this.released && delta > 0) throw new Error('add after wait completed');
    this.count += delta;
  }

  done(): void {
    if (this.count === 0) throw new Error('done without matching add');
    this.count -= 1;
    if (this.count === 0) {
      this.released = true;
      this.gate.resolve();
    }
  }

  wait(): Promise<void> {
    if (this.count === 0) return Promise.resolve();
    return this.gate.promise;
  }
}

async function runJob(wg: WaitGroup, name: string, ms: number) {
  await new Promise((resolve) => setTimeout(resolve, ms));
  console.log(name, 'finished');
  wg.done();
}

async function main() {
  const wg = new WaitGroup();
  const jobs = [
    ['cache', 15],
    ['index', 40],
    ['assets', 25],
  ] as const;
  wg.add(jobs.length); // count before spawning, not after
  for (const [name, ms] of jobs) {
    void runJob(wg, name, ms);
  }
  await wg.wait();
  console.log('all parallel jobs drained');
}

main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

cache finished
assets finished
index finished
all parallel jobs drained

What the code does

WaitGroup Tracks Parallel Task Completion is built around the class WaitGroup and the functions runJob and main.

The cycling part of this snippet is for (const [name, ms] of jobs). Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. A guard precedes the Error: bad state stops the flow there instead of continuing.

Watch out for

  • The guard this.released && delta > 0 short-circuits the flow with an early throw when its condition holds.

Applying it

The primary signature is async function runJob(wg: WaitGroup, name: string, ms: number)

Expect labeled output — all parallel jobs drained — when the file runs.

Execute the file and main walks through runJob, in that order.

Statements that matter

await new Promise((resolve) => setTimeout(resolve, ms));
if (this.count === 0) return Promise.resolve();
if (this.released && delta > 0) throw new Error('add after wait completed');

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
`Error` is raised at the guard (`this.released && delta > 0`), so invalid state never reaches the main logic.
What does WaitGroup Tracks Parallel Task Completion print when run?
Run it as a complete program — the output lines carry labels such as `all parallel jobs drained`.