demo · v134
DisposableStack — many resources, one cleanup
The explainer’s “factory pattern” motivating case: a function that conditionally acquires several resources and needs to dispose all of them in reverse order, even on early return or error. DisposableStack is the runtime side of the proposal — pair it with using to get LIFO cleanup for free. Open and close any combination of resources, then trigger an error to see the stack unwind.
probing DisposableStack…
Build an operation, observe the unwind
0 resources queued for next run.
The code
function setupOperation(opts) {
using stack = new DisposableStack();
const db = stack.use(openDb());
const file = opts.writeOutput ? stack.use(openFile()) : null;
const lock = opts.requireLock ? stack.use(acquireLock()) : null;
return run(db, file, lock);
}
see also
- Explicit resource management (sync) — feature index
- using baseline — sibling concept
- Async resource management
- TC39 proposal — DisposableStack
- ChromeStatus entry