const result = await withCleanup(async (defer) => {
const fileHandle = await getFileHandle();
defer(() => fileHandle.close());
// Carry on
return fileHandle.read();
});
The withCleanup
accepts a function as an argument. That function will be passed a defer
function reference. The defer
function is a mechanism to register some clean-up work that will happen at the completion of the function.
The defer
function should be called with a function as an argument. This function will be stored and called in LIFO order when the wrapped function's returned promise settles. Errors thrown in clean-up functions will not prevent other clean-up functions from running and will instead be accumulated into an AggregateError
and thrown at the end.