Cancellable Task Runner With Cleanup

A cancellable task runner that stops starting new work on abort and always runs registered cleanup, even when a task throws mid-flight.

JavascriptResilience

Code

export class AbortError extends Error {
  constructor(message = "run aborted") {
    super(message);
    this.name = "AbortError";
  }
}

export async function runTasks(tasks, options = {}) {
  const { signal, onCleanup } = options;
  const results = [];
  const throwIfAborted = () => {
    if (signal?.aborted) throw new AbortError();
  };

  throwIfAborted();
  for (const task of tasks) {
    let cleanupRan = false;
    const cleanup = async () => {
      if (cleanupRan) return;
      cleanupRan = true;
      if (onCleanup) await onCleanup();
    };
    try {
      const value = await task({ signal });
      results.push({ ok: true, value });
      await cleanup();
    } catch (err) {
      await cleanup();
      throw err;
    }
    throwIfAborted();
  }
  return results;
}

A batch job that ignores abort keeps starting new work after the user cancelled, and a throwing task skips cleanup and leaks handles.

Use case: engineers running batch jobs that must stop promptly on shutdown

Inputs / outputs

  • Input: a list of task functions, an AbortSignal, optional cleanup hooks per task
  • Output: results for completed tasks, or an abort error with cleanup already run

Error conditions

  • signal already aborted before start
  • a task throws (cleanup still runs)
  • abort observed between tasks

Approach

check the signal before each task; register cleanup before running; on abort stop scheduling further work and throw a typed AbortError after the current task settles.

Implementation

export class AbortError extends Error {
  constructor(message = "run aborted") {
    super(message);
    this.name = "AbortError";
  }
}

export async function runTasks(tasks, options = {}) {
  const { signal, onCleanup } = options;
  const results = [];
  const throwIfAborted = () => {
    if (signal?.aborted) throw new AbortError();
  };

  throwIfAborted();
  for (const task of tasks) {
    let cleanupRan = false;
    const cleanup = async () => {
      if (cleanupRan) return;
      cleanupRan = true;
      if (onCleanup) await onCleanup();
    };
    try {
      const value = await task({ signal });
      results.push({ ok: true, value });
      await cleanup();
    } catch (err) {
      await cleanup();
      throw err;
    }
    throwIfAborted();
  }
  return results;
}

Verification tests

import { test } from "node:test";
import assert from "node:assert/strict";
import { AbortError, runTasks } from "./example.mjs";

test("abort before start runs no task", async () => {
  const controller = new AbortController();
  controller.abort();
  let ran = 0;
  await assert.rejects(
    runTasks([async () => { ran += 1; }], { signal: controller.signal }),
    AbortError,
  );
  assert.equal(ran, 0);
});

test("cleanup runs when a task throws", async () => {
  let cleanups = 0;
  await assert.rejects(
    runTasks([async () => { throw new Error("task failed"); }], {
      onCleanup: async () => { cleanups += 1; },
    }),
    /task failed/,
  );
  assert.equal(cleanups, 1);
});

test("cleanup runs after each success", async () => {
  let cleanups = 0;
  const results = await runTasks([async () => "a", async () => "b"], {
    onCleanup: async () => { cleanups += 1; },
  });
  assert.equal(results.length, 2);
  assert.equal(cleanups, 2);
});

test("abort between tasks stops the run", async () => {
  const controller = new AbortController();
  const ran = [];
  await assert.rejects(
    runTasks(
      [
        async () => { ran.push(1); controller.abort(); return 1; },
        async () => { ran.push(2); return 2; },
      ],
      { signal: controller.signal },
    ),
    AbortError,
  );
  assert.deepEqual(ran, [1]);
});

Dependencies and running

No external dependencies (standard library only).

Runtime: node >= 18 Entry point: node example.mjs

Limitations and error handling

cannot interrupt an already-running task; only cooperative cancellation between tasks.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic