---
title: "Explicit resource management: cleaning up with using and await using"
description: "Learn how JavaScript's using and await using declarations clean up files, locks and connections automatically, how DisposableStack helps, and where they run today."
url: https://www.danny.engineering/article/explicit-resource-management-cleaning-up-with-using-and-await-using
author: Danny
published: 2026-12-04T00:00:00.000Z
updated: 2026-12-02T12:55:00.000Z
tags: ["Javascript"]
---

# Explicit resource management: cleaning up with using and await using

Every program that opens something has to close it. Files, database connections, locks, timers, event listeners, temporary directories: they all need cleaning up, and they need cleaning up even when something throws. In JavaScript that has always meant `try...finally`, and `try...finally` gets awkward fast. Forget it once and you leak a file handle. Open three resources and you end up with three levels of nesting.


Explicit resource management adds two declarations, `using` and `await using`, that tie cleanup to a block. When the block ends, for any reason, the resource is disposed. This article is for JavaScript and TypeScript developers who write code that acquires things and needs to release them, which in practice means most back-end code and a fair amount of front-end and test code. We will start with the problem, build up the API, and finish with where it runs today and when to avoid it.


## The problem with try and finally


Here is a function that writes to a file, using Node's promise-based file API.


```javascript
import { open } from "node:fs/promises";

async function writeReport(path, lines) {
  const file = await open(path, "w");
  try {
    for (const line of lines) {
      await file.write(line + "\n");
    }
  } finally {
    await file.close();
  }
}
```


That is fine for one resource. Add a lock and a second file and it looks like this:


```javascript
async function copyWithLock(lock, from, to) {
  const release = await lock.acquire();
  try {
    const source = await open(from, "r");
    try {
      const target = await open(to, "w");
      try {
        await source.readFile().then((data) => target.write(data));
      } finally {
        await target.close();
      }
    } finally {
      await source.close();
    }
  } finally {
    release();
  }
}
```


The cleanup is far away from the code that needs it, the nesting grows with every resource, and the order of the `finally` blocks has to be kept right by hand.


## The disposable protocol


Explicit resource management starts with two well-known symbols.

- `Symbol.dispose` names a method that cleans up synchronously.
- `Symbol.asyncDispose` names a method that cleans up and returns a promise.

Any object with one of these methods is a disposable. You can add them to your own classes.


```javascript
class TempFlag {
  constructor(target, name) {
    this.target = target;
    this.name = name;
    target.classList.add(name);
  }

  [Symbol.dispose]() {
    this.target.classList.remove(this.name);
  }
}
```


On its own that is just a method with an unusual name. The new declarations are what call it.


## using


A `using` declaration looks like `const`, and like `const` it cannot be reassigned. The difference is that when the enclosing block exits, the value's `Symbol.dispose` method is called.


```javascript
function highlightWhileSaving(form) {
  using flag = new TempFlag(form, "is-saving");

  validate(form);
  save(form);
} // flag[Symbol.dispose]() runs here, even if validate or save throws
```


The rules are short:

- Disposal happens when the block exits, whether by reaching the end, by `return`, by `break` or `continue`, or by an exception.
- If you declare several resources, they are disposed in reverse order, so the last one acquired is the first one released.
- The value can be `null` or `undefined`, in which case nothing is disposed. That makes optional resources easy.
- Any other value without a `Symbol.dispose` method throws a `TypeError` at the declaration, not later.
- The binding must be a simple name. Destructuring, as in `using { a, b } = thing`, is not allowed.

You can also use it in a `for...of` loop, so each item is disposed at the end of its iteration.


```javascript
for (using connection of openConnections(hosts)) {
  connection.ping();
}
```


## await using


Most real cleanup is asynchronous: closing a file, ending a database session, flushing a log. `await using` handles that. At the end of the block it calls `Symbol.asyncDispose` and awaits the result before carrying on. If the object only has `Symbol.dispose`, that is used instead.


`await using` is only allowed where `await` is, so inside async functions and at the top level of modules.


In Node.js, the `FileHandle` objects returned by `open` from `node:fs/promises` already implement `Symbol.asyncDispose`, so the first example becomes:


```javascript
import { open } from "node:fs/promises";

async function writeReport(path, lines) {
  await using file = await open(path, "w");

  for (const line of lines) {
    await file.write(line + "\n");
  }
}
```


And the three-resource version flattens out completely:


```javascript
async function copyWithLock(lock, from, to) {
  using held = await lock.acquire(); // returns an object with Symbol.dispose
  await using source = await open(from, "r");
  await using target = await open(to, "w");

  await target.write(await source.readFile());
}
// disposed in order: target, source, held
```


Each resource is acquired and its cleanup is registered on the same line. There is no way to forget the `close`.


## Writing your own disposables


The pattern works best when the function that acquires a resource returns a disposable. Here is a small database transaction helper.


```javascript
async function beginTransaction(pool) {
  const client = await pool.connect();
  await client.query("BEGIN");
  let committed = false;

  return {
    client,
    async commit() {
      await client.query("COMMIT");
      committed = true;
    },
    async [Symbol.asyncDispose]() {
      if (!committed) {
        await client.query("ROLLBACK");
      }
      client.release();
    },
  };
}

async function transferFunds(pool, from, to, amount) {
  await using tx = await beginTransaction(pool);

  await tx.client.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [amount, from]);
  await tx.client.query("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [amount, to]);
  await tx.commit();
}
```


If either query throws, the transaction rolls back and the connection goes back to the pool. If both succeed, `commit` runs and disposal just releases the connection.


The same shape is useful in tests. A helper that temporarily changes something can restore it automatically.


```javascript
function withEnv(name, value) {
  const previous = process.env[name];
  process.env[name] = value;

  return {
    [Symbol.dispose]() {
      if (previous === undefined) delete process.env[name];
      else process.env[name] = previous;
    },
  };
}

test("uses the staging API", () => {
  using _env = withEnv("API_URL", "https://staging.example.com");
  expect(getApiUrl()).toBe("https://staging.example.com");
});
```


## When cleanup throws: SuppressedError


What happens if the block throws and then the dispose method throws too? With `try...finally`, the error from `finally` silently replaces the original one, which makes bugs very hard to trace.


Explicit resource management keeps both. It throws a `SuppressedError`, whose `error` property is the error from disposal and whose `suppressed` property is the error it replaced.


```javascript
try {
  using res = {
    [Symbol.dispose]() {
      throw new Error("cleanup failed");
    },
  };
  throw new Error("work failed");
} catch (err) {
  console.log(err instanceof SuppressedError); // true
  console.log(err.error.message);      // "cleanup failed"
  console.log(err.suppressed.message); // "work failed"
}
```


If only the dispose method throws, you get that error directly. If only the block throws, you get the original error, as you would expect.


## DisposableStack and AsyncDisposableStack


Sometimes you do not know how many resources you will acquire, or you are working with an API that has a close method but no `Symbol.dispose`. `DisposableStack` and `AsyncDisposableStack` collect cleanup work and run it in reverse order when the stack itself is disposed.

- `use(value)` adds a disposable and returns it.
- `adopt(value, onDispose)` adds any value along with a function to clean it up.
- `defer(fn)` adds a plain cleanup callback.
- `move()` transfers everything to a new stack, leaving the original empty.

```javascript
function watchElements(elements, onResize) {
  using stack = new DisposableStack();

  for (const el of elements) {
    const observer = stack.adopt(new ResizeObserver(onResize), (o) => o.disconnect());
    observer.observe(el);
  }

  const controller = stack.adopt(new AbortController(), (c) => c.abort());
  window.addEventListener("resize", onResize, { signal: controller.signal });

  // Everything set up without throwing, so hand it to the caller
  return stack.move();
}

const watching = watchElements(document.querySelectorAll(".panel"), update);
// later
watching.dispose();
```


The `move` call is the useful trick here. If anything throws while setting up, the `using` declaration disposes the partly built stack. If setup succeeds, ownership moves to the caller, and the now empty original stack disposes nothing.


## Using it in TypeScript


TypeScript has supported `using` and `await using` since version 5.2. Two settings matter:

- Add `esnext` (or the narrower `esnext.disposable`) to `lib` so the `Disposable`, `AsyncDisposable`, `DisposableStack` and `SuppressedError` types are available.
- If your `target` is older than the version that includes the feature, TypeScript rewrites `using` into equivalent `try...finally` code with helpers. That code still needs `Symbol.dispose` and `Symbol.asyncDispose` to exist at runtime, so older environments need a polyfill.

```json
{
  "compilerOptions": {
    "target": "es2022",
    "lib": ["es2022", "esnext.disposable", "dom"]
  }
}
```


Your own disposables can be typed with the built-in interfaces.


```typescript
class Lock implements Disposable {
  constructor(private release: () => void) {}

  [Symbol.dispose](): void {
    this.release();
  }
}
```


Babel also has a plugin that transforms the syntax, if your build uses it.


## Browser and runtime support


As of late 2026, native support is uneven, so check your targets before shipping the syntax untransformed.

- **Chrome and Edge** support it from version 134, released in March 2025.
- **Firefox** supports it from version 141, released in July 2025.
- **Safari** does not support it yet, on macOS or iOS. That is why the feature is not yet Baseline.
- **Node.js** supports it from Node 24, which ships a V8 version that includes it, so it works on Node 24 and later. Node 22, which is still in maintenance LTS, does not support it. `FileHandle` in `node:fs/promises` implements `Symbol.asyncDispose`.

In practice, that means:

- Server code on Node 24 or later can use it directly.
- Browser code that must work in Safari needs to be compiled by TypeScript or Babel, plus a small polyfill for the symbols and, if you use them, `DisposableStack` and `SuppressedError`.

## When not to use it

- **When the lifetime is not a block.** A WebSocket that stays open for the whole session, or a cache that lives as long as the app, does not fit a lexical scope. Use `DisposableStack` with `move`, or ordinary lifecycle code such as a React effect cleanup.
- **When you need to handle cleanup errors differently.** If a failing `close` should be logged and ignored rather than thrown, a hand-written `try...finally` with its own `catch` is clearer.
- **In browser code shipped without a build step.** Until Safari supports it, untransformed `using` is a syntax error there, and a syntax error stops the whole script from running.
- **To replace simple, single cleanups that are already clear.** A short `try...finally` that closes one thing is not a problem worth solving.

## Wrapping up

- `using` calls `Symbol.dispose` and `await using` calls `Symbol.asyncDispose` when the enclosing block exits, however it exits.
- Multiple resources are disposed in reverse order, and `null` or `undefined` are skipped.
- If both the block and the cleanup throw, you get a `SuppressedError` that keeps both errors.
- `DisposableStack` and `AsyncDisposableStack` handle dynamic sets of resources and APIs without dispose methods, and `move` hands ownership to the caller.
- It runs natively in Chromium, Firefox and Node 24 or later. Safari still needs a transform and polyfill.
