demo · v131
DisposableStack for batched cleanup
The companion using demo covers the single-resource case. The proposal also ships DisposableStack — a LIFO collection that owns N resources and disposes them in reverse order. The motivating use case: a function that opens a file, a lock, and a temp directory, and needs all three released no matter which one fails.
log
the pattern
function makeResource(name) {
return {
name,
[Symbol.dispose]() { console.log("disposed:", name); }
};
}
function setup() {
using stack = new DisposableStack();
const file = stack.use(makeResource("file"));
const lock = stack.use(makeResource("lock"));
const tmp = stack.use(makeResource("tmp"));
// ...work...
// on scope exit, disposes tmp, lock, file (reverse order)
}
why a stack
You can chain N using statements, but each declares a new binding name. DisposableStack lets you allocate a variable number of resources in a loop without giving each one a binding. It also supports stack.move() which transfers ownership to a new stack — the canonical use case is a constructor that needs to roll back partial setup if a later step throws, but commit ownership to the instance if it doesn't.