Skip to content
jshacks.dev
Async

How to Use Symbol.asyncDispose for Resources

Use Symbol.asyncDispose and await using in Node.js 24 to close connections and files automatically, in reverse order, even when the code throws an error.

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

Every resource you open in async code has to be closed on every path out: the normal return, the early return and the thrown error. The old way is a try/finally around each resource, and it works until you have three of them and the cleanup code is longer than the logic. Explicit resource management fixes that. You give an object a Symbol.asyncDispose method, declare it with await using, and the runtime calls the method for you when the block ends. This post shows how to use Symbol.asyncDispose for resources in Node.js 24, in what order cleanup runs, what happens when cleanup itself fails and where the feature stops. The syntax comes from the explicit resource management proposal, which is part of the ES2027 specification work and already ships in V8 13.6, the engine inside Node.js 24.

The problem with try and finally

Here is a typical function that opens a connection and a transaction, then has to undo both on any failure.

manual-cleanup.mjsJavaScript
async function openConnection(name) {
  console.log(`open ${name}`);
  return {
    name,
    async close() {
      await new Promise((resolve) => setTimeout(resolve, 5));
      console.log(`close ${name}`);
    },
  };
}

async function main() {
  const db = await openConnection("db");
  try {
    const cache = await openConnection("cache");
    try {
      throw new Error("query failed");
    } finally {
      await cache.close();
    }
  } finally {
    await db.close();
  }
}

main().catch((error) => console.log(error.message));
Text
open db
open cache
close cache
close db
query failed

It is correct, and it nests one level deeper for each resource. Forget one finally, or put the await in the wrong place, and a connection leaks on the one path you did not test.

Making an object disposable

An async disposable is any object with a method stored under the well-known symbol Symbol.asyncDispose. The method takes no arguments and returns a promise. Node.js 24 defines the symbol, so there is nothing to import.

disposable.mjsJavaScript
function openConnection(name) {
  console.log(`open ${name}`);
  return {
    name,
    async [Symbol.asyncDispose]() {
      await new Promise((resolve) => setTimeout(resolve, 5));
      console.log(`close ${name}`);
    },
  };
}

async function main() {
  await using db = openConnection("db");
  await using cache = openConnection("cache");
  console.log(`working with ${db.name} and ${cache.name}`);
}

await main();
console.log("done");
Text
open db
open cache
working with db and cache
close cache
close db
done

The await using declaration binds a variable like const, so you cannot reassign it. When the enclosing block ends, the runtime awaits each disposer in reverse order of declaration: cache closes first, then db. That reverse order is deliberate, because a resource declared later often depends on one declared earlier, the way a transaction depends on its connection.

The declaration is only legal where await is legal: inside an async function, or at the top level of an ES module. It is also valid at the top of a for loop head and in block scopes, not only in functions.

It runs on every exit

The point is that the disposer runs on every path out of the block, including a throw and an early return.

early-exit.mjsJavaScript
function openLock(name) {
  console.log(`lock ${name}`);
  return {
    async [Symbol.asyncDispose]() {
      console.log(`unlock ${name}`);
    },
  };
}

async function run(shouldFail) {
  await using lock = openLock("report");
  if (shouldFail) throw new Error("report failed");
  return "report ok";
}

console.log(await run(false));
try {
  await run(true);
} catch (error) {
  console.log(error.message);
}
Text
lock report
unlock report
report ok
lock report
unlock report
report failed

On the success path the function returns a value, and the unlock still happens before the caller sees it. On the failure path the error propagates after the unlock. Neither path needed a finally.

A disposable that wraps real work

Most of the time you are not writing a disposer from scratch. You are wrapping something that already has a close() method. A small adapter keeps that in one place.

adapter.mjsJavaScript
import { open } from "node:fs/promises";
import { writeFile, rm } from "node:fs/promises";

function disposable(resource, close) {
  return {
    resource,
    [Symbol.asyncDispose]: close,
  };
}

await writeFile("sample.txt", "first line\nsecond line\n");

{
  await using handle = disposable(await open("sample.txt", "r"), async function () {
    await this.resource.close();
    console.log("file closed");
  });
  const text = await handle.resource.readFile({ encoding: "utf8" });
  console.log(text.split("\n")[0]);
}

await rm("sample.txt");
Text
first line
file closed

The disposer is a normal function, so this points at the wrapper object and this.resource is the file handle. In recent Node.js releases, FileHandle objects from node:fs/promises already implement Symbol.asyncDispose themselves, so with Node.js 24 you can usually write await using handle = await open(...) with no adapter at all. The adapter pattern matters for libraries that only offer close(), end() or release().

When disposal throws

Cleanup can fail too, and the spec handles it without losing the first error. If the block threw and a disposer then also throws, the runtime wraps both in a SuppressedError, with the disposer's error in error and the original in suppressed.

suppressed.mjsJavaScript
function flaky() {
  return {
    async [Symbol.asyncDispose]() {
      throw new Error("close failed");
    },
  };
}

try {
  await using resource = flaky();
  throw new Error("work failed");
} catch (error) {
  console.log(error.name);
  console.log(error.error.message);
  console.log(error.suppressed.message);
}
Text
SuppressedError
close failed
work failed

If only the disposer throws, you get that error unchanged. If several disposers throw, the errors chain through nested SuppressedError objects. The practical rule is that a disposer should be written to not throw: catch and log errors about closing a socket that is already gone, and let real failures through.

Mixing sync and async disposal

There are two symbols. Symbol.dispose pairs with using and its method is synchronous. Symbol.asyncDispose pairs with await using and its method may return a promise. An await using declaration also accepts an object that has only Symbol.dispose, and it awaits nothing extra in that case. The reverse is an error: a plain using declaration on an object with only Symbol.asyncDispose throws a TypeError, because a synchronous block cannot wait.

Use Symbol.dispose for things that release instantly, such as removing a listener, and Symbol.asyncDispose for anything that has to flush, drain or close over the network.

Stacks for dynamic cleanup

Sometimes you do not know how many resources you will open until runtime. The built-in AsyncDisposableStack collects cleanup callbacks and runs them in reverse order when disposed.

stack.mjsJavaScript
async function main() {
  await using stack = new AsyncDisposableStack();
  for (const name of ["a", "b", "c"]) {
    console.log(`start ${name}`);
    stack.defer(async () => console.log(`stop ${name}`));
  }
  console.log("running");
}

await main();
Text
start a
start b
start c
running
stop c
stop b
stop a

The stack is itself an async disposable, so declaring it with await using makes the whole group close together. stack.use(resource) adds an object that already has a disposer, and stack.adopt(value, callback) adds a value with its own cleanup function.

Choosing between a stack, a wrapper and a class

Three shapes cover almost every real case, and picking the right one keeps the code short. If one function opens a fixed number of resources, declare each with await using and let the block do the work. If the count is only known at runtime, such as one connection per tenant in a loop, use an AsyncDisposableStack and call stack.use() inside the loop. If a long-lived object owns resources for its whole life, such as a service that holds a database pool and a message consumer, give the class its own Symbol.asyncDispose method that closes the parts in reverse order, and let the code that creates the service declare it with await using.

The class case deserves one habit. Make the disposer idempotent, so calling it twice is harmless. Application shutdown code and a stray finally sometimes both reach it, and a second call that throws "already closed" produces a SuppressedError for something that is not an error. A boolean flag at the top of the method is enough: return early when it is already set, otherwise set it, then close. This is the same discipline as a safe close() on any other resource, and it matters more now that the runtime, and not you, decides when the call happens.

Testing is easier too. A test can create the object in an await using block and assert on state after the block, with no cleanup helper and no afterEach that has to remember what the test opened. If the test fails midway, the disposer still runs, so one failing test does not leave a port bound for the next one. That alone removes a common source of flaky suites, where the second test fails with EADDRINUSE because the first one never reached its cleanup line.

Where the advice stops

Check your target before you adopt this. Node.js 24 runs the syntax natively, so you can use it in server code today. Browsers shipped it later and unevenly, and a bundler or transpiler has to lower it for older targets, so verify the support table for any code that runs in a browser. TypeScript compiles it, with the lib and target settings that the TypeScript documentation describes, and emits helper functions when the target engine lacks support.

Disposal is also not garbage collection. Nothing disposes an object because it became unreachable; the block exit is the only trigger. If you store a disposable in a long-lived field, you still own the job of calling its disposer, usually with await resource[Symbol.asyncDispose]() or an owner that is itself disposable.

Taggedbeginner
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.