DisposableStack Unwinds Cleanup In Reverse
Register cleanup with DisposableStack defer, use, and adopt, then dispose once and watch callbacks run in reverse order.
Code
// DisposableStack registers cleanup and runs it in reverse order
const events = [];
function openResource(name) {
events.push('open:' + name);
return {
name,
[Symbol.dispose]() {
events.push('close:' + name);
},
};
}
function main() {
const stack = new DisposableStack();
stack.defer(() => events.push('defer:last'));
stack.use(openResource('db'));
stack.adopt('cache', (value) => events.push('adopt:' + value));
stack.defer(() => events.push('defer:first'));
console.log('disposed before:', stack.disposed);
const returned = stack.dispose();
console.log('dispose returned:', returned);
console.log('disposed after:', stack.disposed);
console.log('events:', events.join(' | '));
}
main();Output
Captured from a sandboxed run of this snippet in the build pipeline.
disposed before: false
dispose returned: undefined
disposed after: true
events: open:db | defer:first | adopt:cache | close:db | defer:lastInside the snippet
DisposableStack Unwinds Cleanup In Reverse keeps everything in the functions openResource and main.
The return value is newly constructed — inputs are never handed back.
Using it
Entry signature: function openResource(name)
The demo output is labeled (disposed before:, dispose returned:, disposed after:), so every printed line maps back to its originating operation.
main sequences openResource; executing the file runs that flow once.
Key statements
stack.adopt('cache', (value) => events.push('adopt:' + value));
stack.defer(() => events.push('defer:first'));
stack.defer(() => events.push('defer:last'));
Interactive Tools for This Topic
FAQ
- Does `openResource` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- What does DisposableStack Unwinds Cleanup In Reverse print when run?
- The script runs standalone; its 4 labeled outputs include `disposed before:`, `dispose returned:`, `disposed after:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.