with-defer
Version:
Run a function with an injected go-like defer helper
37 lines (35 loc) • 788 B
JavaScript
// src/error.ts
var AggregateError = class extends Error {
constructor(errors, message = "") {
super(message);
this.message = message;
this.name = "AggregateError";
this.errors = [...errors];
}
};
// src/cleanup.ts
async function runWithDefer(func) {
const onCleanup = [];
const defer = (deferredFn) => {
onCleanup.unshift(deferredFn);
};
try {
return await func(defer);
} finally {
let errors = [];
for (const onCleanupFn of onCleanup) {
try {
await onCleanupFn();
} catch (err) {
errors.push(err);
}
}
if (errors.length) {
throw new AggregateError(errors, "One or more exceptions caught while executing deferred clean-up functions");
}
}
}
export {
AggregateError,
runWithDefer
};