Skip to content
jshacks.dev
Fundamentals

Explicit Resource Management With using and await using

The using declaration disposes a resource when its block ends, in reverse order, even after errors. See Symbol.dispose, await using and SuppressedError.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, npm, TypeScript and Vite logos.

Closing a file, releasing a lock, ending a transaction and clearing a timer all follow one shape: acquire, use, release even if the use fails. JavaScript has had one way to write it, try and finally, and its cost is ceremony. Each resource needs a variable declared outside the block, a finally that checks whether the acquisition succeeded, and a careful order when there are several. The using declaration, from the explicit resource management proposal that is part of ES2027 and already shipped in current engines, moves that shape into the language. This post covers using and await using, the disposal order and error rules, the stacks that collect cleanups and the tests that pin the behavior. Output is from Node.js 24 as an ES module, which runs it natively. The older pattern is covered in the post on try, catch and finally, and the symbols involved are in the post on symbols.

The basic declaration

A value with a [Symbol.dispose]() method can be bound with using. When the block ends, the method is called.

JavaScript
function openResource(name, log) {
  log.push(`open ${name}`);
  return {
    name,
    read: () => `data from ${name}`,
    [Symbol.dispose]() {
      log.push(`close ${name}`);
    },
  };
}

const log = [];

function work() {
  using file = openResource("a.txt", log);
  log.push(file.read());
  return "result";
}

console.log(work());
console.log(log);

try {
  (() => {
    using file = openResource("b.txt", log);
    throw new Error("failed while using");
  })();
} catch (error) {
  console.log(error.message);
}

console.log(log.slice(-2));
Text
result
[ 'open a.txt', 'data from a.txt', 'close a.txt' ]
failed while using
[ 'open b.txt', 'close b.txt' ]

The resource was closed after the function returned, and the return value was unaffected. In the second case the block threw, and the resource was still closed before the error reached the catch. That is the guarantee of finally, written once at the point of acquisition, with no variable to declare early and no flag to check. A using binding is const-like: it cannot be reassigned.

Disposal order

Several using declarations in one block dispose in the reverse order of their declaration, last in first out. That is the order in which dependencies unwind.

JavaScript
const trace = [];

const make = (name) => ({
  [Symbol.dispose]() {
    trace.push(`dispose ${name}`);
  },
});

{
  using connection = make("connection");
  using statement = make("statement");
  using cursor = make("cursor");
  trace.push("body");
}

console.log(trace);

const skipped = [];
{
  using maybe = null;
  using nothing = undefined;
  using real = { [Symbol.dispose]: () => skipped.push("real disposed") };
  skipped.push("block ran");
}
console.log(skipped);

try {
  eval("{ using bad = {}; }");
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
[ 'body', 'dispose cursor', 'dispose statement', 'dispose connection' ]
[ 'block ran', 'real disposed' ]
TypeError: Symbol(Symbol.dispose) is not a function

The cursor closed first, then the statement, then the connection, which is the order in which a database driver needs them released. A null or undefined value is permitted and skipped, so a resource created only under a condition can still be bound. A value without a [Symbol.dispose] method is a TypeError at the declaration, not later at cleanup, which gives an early and clear failure.

await using for asynchronous cleanup

Some cleanup takes time: flushing a buffer, closing a socket, committing a transaction. await using calls [Symbol.asyncDispose]() and waits for the promise it returns, and it can only appear where await is allowed.

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

const events = [];

function openConnection(name) {
  events.push(`open ${name}`);
  return {
    name,
    async query(sql) {
      await sleep(1);
      return `${name}: ${sql}`;
    },
    async [Symbol.asyncDispose]() {
      await sleep(5);
      events.push(`closed ${name}`);
    },
  };
}

async function run() {
  await using primary = openConnection("primary");
  await using replica = openConnection("replica");
  events.push(await primary.query("select 1"));
  events.push(await replica.query("select 2"));
  return "done";
}

console.log(await run());
console.log(events);

{
  using plain = { [Symbol.dispose]: () => events.push("sync dispose") };
  await using later = { [Symbol.asyncDispose]: async () => events.push("async dispose") };
}
console.log(events.slice(-2));
Text
done
[
  'open primary',
  'open replica',
  'primary: select 1',
  'replica: select 2',
  'closed replica',
  'closed primary'
]
[ 'async dispose', 'sync dispose' ]

Both connections were closed after the function body, each cleanup was awaited, and the replica closed before the primary. Mixing the two kinds in one block works: the declarations dispose in reverse order, each by its own method, and await using waits for asynchronous ones. The function's caller sees the result only after every disposal finishes, so a function that returns a value does not leave a transaction half closed.

When the body and the disposal both throw

If the block throws and a disposal then throws as well, the second error would normally replace the first and hide it. The language instead raises a SuppressedError that holds both.

JavaScript
const resource = {
  [Symbol.dispose]() {
    throw new Error("disposal failed");
  },
};

try {
  (() => {
    using r = resource;
    throw new Error("body failed");
  })();
} catch (error) {
  console.log(error.name, error instanceof SuppressedError);
  console.log(error.error.message, "|", error.suppressed.message);
  console.log(error.message);
}

try {
  (() => {
    using r = resource;
  })();
} catch (error) {
  console.log(error.name, error.message);
}
Text
SuppressedError true
disposal failed | body failed
An error was suppressed during disposal
Error disposal failed

The later failure, from the disposal, is in error.error, and the earlier one from the body, which it suppressed, is in error.suppressed. When the body succeeds and only the disposal fails, that error is thrown as itself. Code that catches around a using block should be ready for a SuppressedError, and log both fields, because the root cause is usually the earlier one in suppressed.

DisposableStack for dynamic cleanup

A stack collects cleanups at runtime and disposes them all together in reverse order. It suits setup that acquires resources in steps, with branches or loops, where a fixed list of using lines does not fit.

JavaScript
const order = [];

function setup(options) {
  const stack = new DisposableStack();

  const first = stack.use({ [Symbol.dispose]: () => order.push("first resource") });
  stack.defer(() => order.push("deferred cleanup"));
  stack.adopt({ id: 7 }, (value) => order.push("adopted " + value.id));

  if (options.second) {
    stack.use({ [Symbol.dispose]: () => order.push("second resource") });
  }

  return stack;
}

const stack = setup({ second: true });
order.push("in use");
stack.dispose();
console.log(order, stack.disposed);

const moved = setup({ second: false });
const transferred = moved.move();
console.log(moved.disposed, transferred.disposed);
transferred.dispose();
console.log(order.slice(-3));
Text
[
  'in use',
  'second resource',
  'adopted 7',
  'deferred cleanup',
  'first resource'
] true
true false
[ 'adopted 7', 'deferred cleanup', 'first resource' ]

The stack accepted a disposable with use(), a plain callback with defer() and a value with its own cleanup function with adopt(), and dispose() ran them in reverse order. move() transfers ownership to a new stack and leaves the old one empty, which is how a function hands a half-built set of resources to its caller only if setup succeeds. AsyncDisposableStack is the async version.

Adapting existing resources

Most existing APIs have a close() method and no Symbol.dispose. A tiny wrapper gives them one without changing them.

JavaScript
class Handle {
  closed = false;
  close() {
    this.closed = true;
  }
}

function disposable(resource, method = "close") {
  return {
    resource,
    [Symbol.dispose]: () => resource[method](),
  };
}

const handle = new Handle();

{
  using wrapped = disposable(handle);
  console.log(wrapped.resource.closed);
}

console.log(handle.closed);

const timer = (ms) => {
  const id = setTimeout(() => {}, ms);
  return { id, [Symbol.dispose]: () => clearTimeout(id) };
};

{
  using pending = timer(10_000);
  console.log(typeof pending.id);
}
console.log("timer cleared, process can exit");
Text
false
true
object
timer cleared, process can exit

The wrapper called close() when the block ended. The timer example is a typical use: a timeout is created for the duration of a block and cleared automatically. A growing number of APIs implement the protocol directly, so check the documentation of the one you use before writing an adapter.

Why this matters beyond tidiness

The garbage collector frees memory and does nothing about the handle behind it, as the post on garbage collection explains: a file descriptor, a socket or a lock stays open until you release it, however unreachable the object that held it. That is why every long-running service eventually meets a descriptor leak, usually in an error path where the cleanup line was skipped. A using declaration places the release at the point of acquisition, so the error path and the success path share one cleanup, and reviewers can see at a glance that a resource is managed. The benefit is largest where the cleanup is easy to forget and expensive to miss.

Where using is the wrong tool

If a resource must outlive the function that created it, such as a connection pool handed to the rest of the application, a block-scoped declaration disposes too early. If cleanup depends on knowing how the block ended, success or failure, try and finally or catch can distinguish the cases, and using cannot. And if the code must run in an environment without support, a transpiler is required.

Support is current: Node.js 24, Chrome 134 and Firefox 141 run the syntax, and TypeScript 5.2 and later compile it, with lib set to include esnext.disposable. Safari has not shipped it at the time of writing, so a transpiler or a fallback to try and finally is still needed for that target.

A test for the guarantee

The property worth pinning in a test is that the resource closes on every exit path. Assert both paths and the order.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

function tracked(log, name) {
  return { [Symbol.dispose]: () => log.push(name) };
}

test("resources close on return and on error, in reverse order", () => {
  const log = [];

  function normal() {
    using a = tracked(log, "a");
    using b = tracked(log, "b");
    return "ok";
  }

  function failing() {
    using a = tracked(log, "a");
    throw new Error("boom");
  }

  assert.equal(normal(), "ok");
  assert.throws(failing, /boom/);
  assert.deepEqual(log, ["b", "a", "a"]);
});

Run it with node --test on Node.js 24. The expected log lists b before a for the normal path, and a once more for the failing one. A refactor that moves acquisition outside the block, or that returns a resource instead of using it, breaks the first assertion at once.

The proposal is specified in the explicit resource management repository, and MDN documents the syntax on its using reference page and await using page.

Also inAsync
Taggedes2027
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.