JavaScriptFundamental (ES6), part 2
Release resources with try/finally in JavaScript
43 Acquire and release, whatever happens
hardWrite withTill(name, use) that opens a resource, hands it to use, and closes it in a finally. Prove it closes on success, on a throw, and innermost-first when nested. Then drop the await and watch it close the till while the work is still running.
Stuck? Three hints, smallest first
- 1. Acquire outside the
try, release in thefinally. If the acquire throws there is nothing to release. - 2. Nesting is a stack: the inner
finallyruns before the outer one. - 3. The broken version differs from the correct one by one keyword — the same keyword as exercise 39.
const log = [];
let open = 0;
const openTill = (name) => {
open++;
log.push('open ' + name);
return {
name,
print: (line) => 'receipt from ' + name + ': ' + line,
close: () => { open--; log.push('close ' + name); },
};
};
async function withTill(name, use) {
const till = openTill(name);
try { return await use(till); }
finally { till.close(); }
}
async function withTillBroken(name, use) {
const till = openTill(name);
try { return use(till); } // no await: the finally runs at once
finally { till.close(); }
}
const receipt = await withTill('yaba', async (till) => {
await Promise.resolve();
return till.print('₦2,500');
});
const afterSuccess = [open, log.slice()];
log.length = 0;
const failure = await withTill('lekki', async () => {
throw new Error('printer jammed');
}).catch((err) => err.message);
const afterFailure = [open, log.slice()];
log.length = 0;
const nested = await withTill('outer', (a) => withTill('inner', async (b) => a.name + ' + ' + b.name));
const nestedOrder = log.slice();
log.length = 0;
const broken = await withTillBroken('ajah', (till) =>
Promise.resolve().then(() => {
log.push('used ' + till.name + ', open tills: ' + open);
return till.name;
})
);
const brokenOrder = log.slice();
console.log('receipt :', receipt);
console.log('failure :', failure, afterFailure);
console.log('nested :', nestedOrder);
console.log('broken :', brokenOrder);
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('the value comes back from use()', receipt, 'receipt from yaba: ₦2,500');
test('and the till was closed on the way out', afterSuccess, [0, ['open yaba', 'close yaba']]);
test('a throw inside use() closes it too', afterFailure, [0, ['open lekki', 'close lekki']]);
test('without swallowing the failure', failure, 'printer jammed');
test('nested resources close innermost first', nestedOrder, ['open outer', 'open inner', 'close inner', 'close outer']);
test('and nesting still produces the value', nested, 'outer + inner');
test('drop the await and the till is closed before the work touches it', brokenOrder, ['open ajah', 'close ajah', 'used ajah, open tills: 0']);
test('every till opened in this exercise ended up closed', open, 0);
This is the resource pattern in five lines, and the ordering of those five lines is the whole content. Acquire before the try, because a failed acquire has nothing to release and putting it inside gives you a finally that closes an undefined till. Release in the finally, because that is the only branch that runs on every exit: value, throw, and the return and continue from exercise 32.
Nesting works for free, and the fifth assertion is why: each finally belongs to its own call frame, so unwinding closes the inner till first. That is the same last-in-first-out discipline as a stack of locks, and taking them in a consistent order is what keeps two callers from deadlocking on each other.
The seventh assertion is exercise 39's missing keyword wearing different clothes, and it is worth seeing twice because the symptom here is so much worse. The till is closed, open is back to zero, and only then does the work run — against a closed resource. In real code that is a query on a released connection or a write to a closed file handle, and it fails intermittently, under load, in a way that looks like a driver bug.
The modern language has using and await using with Symbol.dispose, which is this pattern promoted into syntax. Until it is everywhere, a withX helper is how you make sure no caller has to remember the finally at all.