Sub topic 2
When and in What Order Resources Are Disposed
This chapter assumes you know block scoping, try/finally, async/await, and the Symbol.dispose protocol covered in the previous chapter.
Disposal Timing and Reverse Order
A using resource is disposed when its enclosing block exits. That includes a normal exit, a return, a break, or a thrown error. When a block holds several resources, they are disposed in reverse order of declaration, so the last one opened is the first one closed. This matters because later resources often depend on earlier ones. For example, a transaction depends on the connection it runs on.
function res(name) {
return { [Symbol.dispose]() { console.log(`close ${name}`); } };
}
{
using conn = res("connection");
using tx = res("transaction");
console.log("work");
}
// work
// close transaction
// close connectionAsynchronous Cleanup with await using
await using calls Symbol.asyncDispose and awaits the result before the next resource is disposed. You can only write it inside an async function or at the top level of a module. If the object has no Symbol.asyncDispose, the runtime uses Symbol.dispose instead.
async function main() {
await using file = {
async [Symbol.asyncDispose]() {
await new Promise((r) => setTimeout(r, 10));
console.log("flushed and closed");
},
};
console.log("writing");
}
main(); // writing, flushed and closedOptional Resources: null, undefined, and TypeErrors
You can assign null or undefined to a using declaration. Disposal is then skipped, which makes conditional resources easy to write. Any other value without the right dispose method throws a TypeError immediately, at the declaration, not later when the block exits.
{
using maybe = Math.random() > 0.5 ? res("cache") : null; // fine either way
}
try {
using bad = {}; // TypeError: no Symbol.dispose
} catch (e) {
console.log(e instanceof TypeError); // true
}When Cleanup Fails: SuppressedError
Sometimes the block throws and then a disposer throws too. In that case the runtime keeps both errors by wrapping them in a SuppressedError. Its error property holds the newer error, from the disposer. Its suppressed property holds the earlier one. If several disposers fail, the wrappers nest, one level for each failure.
try {
using r = { [Symbol.dispose]() { throw new Error("cleanup failed"); } };
throw new Error("body failed");
} catch (e) {
console.log(e.error.message); // cleanup failed
console.log(e.suppressed.message); // body failed
}Exercise
A block declares using a, then using b, then throws "X". Disposing b throws "B" and disposing a throws "A". What are e.error.message, e.suppressed.error.message, and e.suppressed.suppressed.message?
Show answer
b is disposed first, giving SuppressedError(error B, suppressed X). Disposing a then wraps that: SuppressedError(error A, suppressed the first wrapper). So the answers are "A", "B", and "X".