Sub topic 4
Declaring Resources with using
This chapter assumes you know block scoping with let and const, how try/finally behaves, and how to give an object a Symbol.dispose method, which the previous chapter covered. Here the focus is the using declaration itself: what it binds, when it registers a resource, what happens on each way out of a block, and the mistakes people make most often when they first adopt it.
The shape of a using declaration
A using declaration looks like a const declaration with a different keyword:
function openResource(name) {
console.log(`open ${name}`);
return {
name,
closed: false,
[Symbol.dispose]() {
this.closed = true;
console.log(`close ${name}`);
},
};
}
{
using res = openResource("log-file");
console.log(`working with ${res.name}, closed=${res.closed}`);
}
console.log("after block");
// open log-file
// working with log-file, closed=false
// close log-file
// after blockThree things happen here:
- The initializer
openResource("log-file")runs and produces a value. - The runtime checks that the value is disposable, looks up its
Symbol.disposemethod, and records the value and the method in a list that belongs to the enclosing block. - When control leaves the block, the runtime calls each recorded method with the resource as
this.
You never write the call to Symbol.dispose yourself. The block owns the resource, and leaving the block releases it.
What using desugars to
A rough mental model is that using rewrites the rest of the block into a try/finally. These two functions behave the same in the common case:
function openResource(name) {
return { name, [Symbol.dispose]() { console.log(`close ${name}`); } };
}
function manual() {
const res = openResource("db");
try {
console.log(`query via ${res.name}`);
return "done";
} finally {
res[Symbol.dispose]();
}
}
function declarative() {
using res = openResource("db");
console.log(`query via ${res.name}`);
return "done";
}
console.log(manual());
console.log(declarative());
// query via db
// close db
// done
// query via db
// close db
// doneThe model is only approximate. The real semantics differ from hand-written try/finally in a few ways that matter:
| Aspect | Hand-written try/finally | using declaration |
|---|---|---|
| When the dispose method is looked up | When `finally` runs | At the declaration |
| Missing dispose method | Fails at cleanup time, after the work ran | `TypeError` at the declaration, before any work |
| Several resources | Nested `try` blocks, one per resource | One declaration per resource, unwound automatically |
| Cleanup throws while the body also threw | The cleanup error silently replaces the body error | Both errors are kept (see the SuppressedError chapter) |
| Binding mutability | Whatever you chose | Always immutable, like `const` |
The first two rows are the subject of the next section.
Registration happens at the declaration
The runtime reads Symbol.dispose once, at the moment the declaration runs, and stores the function it found. Changing the property later has no effect on cleanup:
const res = {
[Symbol.dispose]() { console.log("original dispose"); },
};
{
using r = res;
r[Symbol.dispose] = () => console.log("replacement dispose");
}
// original disposeBecause the method is fetched early, a value that is not disposable fails fast:
function work() {
using r = { name: "not disposable" };
console.log("this line never runs");
}
try {
work();
} catch (e) {
console.log(e instanceof TypeError); // true
}Failing at the declaration is the useful behavior. With manual cleanup, a missing close method only shows up after the work has already run and possibly left things half-finished. With using, nothing after the bad declaration runs. Any resources declared earlier in the same block are still disposed, because they were already registered.
null and undefined are the exception to this check. They are allowed and skipped, and a later chapter covers that case. Every other non-object value, such as a string or number, throws.
The binding is immutable
A using binding cannot be reassigned. Assigning to it throws a TypeError, the same as assigning to a const:
function openResource(name) {
return { name, [Symbol.dispose]() { console.log(`close ${name}`); } };
}
try {
using r = openResource("first");
r = openResource("second");
} catch (e) {
console.log(e instanceof TypeError); // true
}
// close first
// trueThe rule protects the bookkeeping. The runtime disposes the value it registered, not whatever the variable holds later. If reassignment were allowed, the code would look as though second were being managed while first was the one actually closed. Making the binding immutable keeps what you see and what is disposed the same.
The object itself is still mutable. You can call its methods and change its properties as usual. Only the binding is fixed.
Like let and const, a using binding is in the temporal dead zone until its declaration runs. It is visible only inside its block.
Every exit path disposes
The main reason to use using is that you stop thinking about how a block ends. Any completion of the block runs disposal:
function openResource(name) {
return { name, [Symbol.dispose]() { console.log(` close ${name}`); } };
}
function viaReturn() {
using r = openResource("return");
return "returned";
}
function viaThrow() {
using r = openResource("throw");
throw new Error("boom");
}
console.log(viaReturn());
try {
viaThrow();
} catch (e) {
console.log(`caught ${e.message}`);
}
for (const n of [1, 2, 3]) {
using r = openResource(`iteration ${n}`);
if (n === 1) continue;
if (n === 2) break;
}
outer: {
using r = openResource("labeled");
break outer;
}
// output:
// close return
// returned
// close throw
// caught boom
// close iteration 1
// close iteration 2
// close labeledNotice the loop. The using sits in the loop body, which is a block that is entered and left on every iteration. Each iteration gets a fresh resource and disposes it before the next iteration starts, whether the iteration ends normally, with continue, or with break. Iteration 3 never runs, so it never opens anything.
After disposal, the block's original completion continues. A return still returns its value, a break still breaks, and a thrown error still propagates. Disposal runs in between and leaves the completion alone, unless the dispose method itself throws, which a later chapter covers.
Multiple bindings in one declaration
As with const, you can declare several resources in one statement:
function openResource(name) {
console.log(`open ${name}`);
return { name, [Symbol.dispose]() { console.log(`close ${name}`); } };
}
{
using a = openResource("a"), b = openResource("b");
console.log("work");
}
// open a
// open b
// work
// close b
// close aThis behaves exactly like two separate using statements. Each binding is registered as soon as its own initializer finishes. If openResource("b") threw, a would already be registered and would still be closed. The reverse order of disposal is deliberate, and the next chapter explains why.
Common mistakes
Returning a resource you declared with using
using means "this scope owns the resource." If the function is supposed to hand the resource to its caller, using is the wrong tool:
function openResource(name) {
const r = {
name,
open: true,
[Symbol.dispose]() { r.open = false; },
};
return r;
}
function broken() {
using conn = openResource("conn");
return conn; // disposed before the caller receives it
}
function correct() {
return openResource("conn"); // caller decides how to manage it
}
console.log(broken().open); // false
console.log(correct().open); // true
{
using c = correct();
console.log(c.open); // true
}The rule: whoever writes using owns the resource. Factories return plain values, and the code that consumes them declares them with using. When a function must set up several resources and then hand them all over, DisposableStack.prototype.move() does that safely, as a later chapter shows.
Letting a reference escape
using disposes the object. It does not make the object unreachable. A closure, callback, or property that captured the resource can still use it after the block ends. Disposable objects should refuse to work once disposed, for example by throwing from methods called after close, so that this mistake surfaces as an error instead of silent misbehavior.
Using a resource without a block
Disposal is tied to the nearest enclosing block, function body, or module. A using at the top of a long function keeps the resource open until the function returns. If you only need the resource for a few lines, put those lines in their own bare { ... } block so it is released as early as possible.
Expecting using to work with arbitrary close methods
using only calls Symbol.dispose. An object with close(), release(), or end() but no Symbol.dispose throws at the declaration. Either add the symbol method to your own classes, or wrap third-party objects with DisposableStack.adopt, covered later.
Exercise
What does this code print, and why?
function make(name) {
return { [Symbol.dispose]() { console.log(dispose ${name}); } };
}
function f() {
using x = make("x");
using y = 42;
console.log("unreachable?");
}
try { f(); } catch (e) { console.log(e.constructor.name); }
Show answer
It prints "dispose x" and then "TypeError". The declaration using y = 42 throws a TypeError because 42 is neither an object with Symbol.dispose nor null or undefined. The console.log after it never runs. The resource x was already registered, so the block still disposes it before the error propagates to the catch.
Exercise
A teammate writes function getLogger() { using log = openLog(); log.write("init"); return log; } and reports that every write after the call fails with "log closed". Explain the cause and give a fix.
Show answer
The using declaration makes getLogger's body the owner of log, so the log is disposed when the function returns, before the caller gets it. Ownership must belong to the caller. Change the factory to create and initialize the log with const (or with a DisposableStack and move() if setup can fail partway) and return it, then have the caller write using log = getLogger();.
Exercise
Inside a using block, code runs r[Symbol.dispose] = newFn; where r is the using binding. Which function runs at block exit, and would r = other; behave differently?
Show answer
The original dispose method runs, because using looks up and stores the method when the declaration executes. Changing the property later has no effect. r = other; is different: it throws a TypeError immediately because using bindings are immutable, like const. The originally registered resource is still disposed as the block exits with that error.