4 ms·
The nice thing is that the `defer` pattern can be easily built on top of the `using` pattern, and indeed the `DisposableStack` and `AsyncDisposableStack` object
by WorldMaker 3y ago
The nice thing is that the `defer` pattern can be easily built on top of the `using` pattern, and indeed the `DisposableStack` and `AsyncDisposableStack` objects also included in the TC-39 proposal for built-ins directly support it:
let connection = getConnection()
using stack = new DisposableStack()
stack.defer(() => connection.dispose())
The proposal even notes the `defer` method name was borrowed from golang.
Though in practice I think the `adopt` method will be the nicer, more common pattern for transitional things before `[Symbol.dispose]` becomes more widely utilized:
using stack = new DisposableStack()
const connection = stack.adopt(getConnection(), c => c.dispose())