JavaScriptFundamental (ES6), part 2
Disposal stack for multiple resources in JavaScript
55 A disposal stack that finishes the job
hardExercise 43 released one resource. Now hold several: use(name, dispose) to register and disposeAll() to release them all in reverse order. A release that throws must not prevent the rest, and every failure must be reported — so collect them into an AggregateError.
Stuck? Three hints, smallest first
- 1.
pop()in a loop gives you reverse order and empties the stack as it goes. - 2. Wrap each release in its own
try, or the first failure skips everything after it. - 3. Wrap each failure with
causeso the report says which resource, and still carries why.
function disposalStack() {
const entries = [];
return {
use(name, dispose) { entries.push({ name, dispose }); return name; },
get size() { return entries.length; },
async disposeAll() {
const failures = [];
while (entries.length) {
const { name, dispose } = entries.pop(); // reverse order, and it empties
try { await dispose(); }
catch (err) { failures.push(new Error('could not release ' + name, { cause: err })); }
}
if (failures.length) {
throw new AggregateError(failures, failures.length + ' resource(s) failed to release');
}
},
};
}
const released = [];
const clean = disposalStack();
clean.use('database connection', () => released.push('database connection'));
clean.use('temp file', async () => { await Promise.resolve(); released.push('temp file'); });
clean.use('till printer', () => released.push('till printer'));
const sizeBefore = clean.size;
const noComplaint = await clean.disposeAll().then(() => 'released cleanly', (err) => err.message);
const orderOut = released.slice();
const sizeAfter = clean.size;
const messy = disposalStack();
const attempted = [];
messy.use('database connection', () => { attempted.push('database connection'); });
messy.use('temp file', () => { attempted.push('temp file'); throw new Error('file already gone'); });
messy.use('till printer', async () => { attempted.push('till printer'); throw new Error('printer not responding'); });
const failure = await messy.disposeAll().catch((err) => err);
const reported = failure.errors.map((err) => err.message);
const rootCauses = failure.errors.map((err) => err.cause.message);
const twice = await messy.disposeAll().then(() => 'nothing left to do', (err) => err.message);
console.log('clean :', noComplaint, orderOut);
console.log('messy :', failure.message);
console.log('reported:', reported);
console.log('causes :', rootCauses);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('everything is released, in reverse order of registration', orderOut, ['till printer', 'temp file', 'database connection']);
test('a clean run throws nothing', [sizeBefore, noComplaint, sizeAfter], [3, 'released cleanly', 0]);
test('a release that throws does not stop the ones behind it', attempted, ['till printer', 'temp file', 'database connection']);
test('every failure is reported, not just the first', reported, ['could not release till printer', 'could not release temp file']);
test('and each one names the resource while keeping the real reason', rootCauses, ['printer not responding', 'file already gone']);
test('the report is one AggregateError, so one catch handles it', [failure instanceof AggregateError, failure.message], [true, '2 resource(s) failed to release']);
test('the stack is emptied even when releases failed', messy.size, 0);
test('so disposing twice is a harmless no-op', twice, 'nothing left to do');
Cleanup code is the last place you want a single failure to be decisive, and the third assertion is the whole exercise: the printer failed first and the database connection was still closed. The naive loop — one try around the whole thing — closes resources until something throws and then abandons the rest, which is how a failed file delete leaks a connection.
So each release gets its own try, and the failures are collected rather than thrown. That leaves the question of what to do with a list of failures, and AggregateError from exercise 36 is the answer: one throw, one catch for the caller, every reason preserved. Wrapping each one with cause is what makes the report readable — "could not release till printer" says which, and the cause says why, and neither would be recoverable from the other alone.
Reverse order is not decoration. Resources acquired in order usually depend on each other, so a transaction must be closed before its connection and a stream flushed before its file handle. pop() gives that ordering for free and empties the stack as it goes, which is what makes the last two assertions true: nothing is left registered even after a failure, so a second disposeAll does nothing rather than double-releasing.
This is the shape the language is standardising as AsyncDisposableStack, with await using and Symbol.asyncDispose handling the registration and the finally for you. The semantics are the ones here — reverse order, all releases attempted, failures aggregated — so writing it once is the fastest way to understand what the syntax will be doing on your behalf.