Sub topic 1
Why Manual Cleanup Breaks: The try/finally Problem
Prerequisites
This chapter assumes you know block scoping with let and const, how try/catch/finally behaves, and well-known symbols such as Symbol.iterator. Later chapters also rely on Promises and async/await.
The try/finally Problem
Files, sockets, locks and timers must be released when you finish with them. The usual tool is try/finally. It works, but each resource adds another layer of nesting. The cleanup code also sits far from the line that acquired the resource. If you forget the finally, or acquire a second resource before entering the try, an early return or a thrown error leaks that resource.
function openResource(name) {
console.log(`open ${name}`);
return {
name,
[Symbol.dispose]() {
console.log(`close ${name}`);
},
};
}
function withoutUsing() {
const res = openResource("db");
try {
return `used ${res.name}`;
} finally {
res[Symbol.dispose]();
}
}Meet Symbol.dispose and Symbol.asyncDispose
Symbol.dispose and Symbol.asyncDispose are well-known symbols, like Symbol.iterator. They give cleanup methods a standard name. The language calls Symbol.dispose synchronously. It calls Symbol.asyncDispose and awaits the Promise that it returns.
Making an Object Disposable
A disposable object is any object that has a [Symbol.dispose]() method. An async disposable object has [Symbol.asyncDispose]() instead. openResource above already returns a disposable object. Make dispose idempotent, which means calling it twice is harmless, because more than one owner may try to clean up.
Declaring Resources with using
A using declaration binds a disposable value to the enclosing block. When the block exits, the runtime calls its dispose method. The block can exit normally, through return, or through a thrown error. If you declare several resources, they are disposed in reverse order.
function withUsing() {
using res = openResource("db");
return `used ${res.name}`;
} // res is disposed here, after the return value is computed
{
using a = openResource("a");
using b = openResource("b");
console.log("work");
}
// open a, open b, work, close b, close aLike const, a using binding cannot be reassigned.
Exercise
A block declares using x = openResource("x"); using y = openResource("y"); and then throws an error. What is logged, and in what order?
Show answer
"open x", "open y", then "close y", "close x". Disposal still runs when the block throws, in reverse order of declaration, and the error then propagates.