@dacodedbeat/with-defer-js
v1.0.0
Published
A simple and lightweight JavaScript library for scheduling deferred function callbacks to execute after a function, like Golang.
Maintainers
Readme
with-defer.js
with-defer.js is a simple and lightweight JavaScript library that allows you to schedule function callbacks after
the execution of a function, just like Golang’s defer. Perfect for cleanup tasks, error handling, and more for both
asynchronous and synchronous operations.
Why with-defer.js?
Inspired by Golang’s defer, this library gives you the same power in JavaScript.
In Go, defer lets you schedule a function to run after the current function ends - whether it finishes normally or
with an error. This is useful for tasks like closing files or releasing resources without messing up the main flow of
the program.
In JavaScript, especially with async operations, you often need similar cleanup tasks, but there's no built-in defer
keyword. This library brings the simplicity of Go's defer to JavaScript.
TL;DR: Stack up tasks, run them after your main code finishes (even if it crashes), and keep your code tidy.
Golang vs. with-defer.js
Golang:
func main() {
defer cleanup1()
defer cleanup2()
// do stuff
}with-defer.js:
import { withDefer } from '@dacodedbeat/with-defer-js';
const mainFunction = (defer) => {
defer(() => console.log("Cleanup 1"));
defer(() => console.log("Cleanup 2"));
// do stuff
};
withDefer(mainFunction)();How the two align
Automatic Execution After Function Ends: Just like in Go, functions in
with-defer.jsrun after the main function finishes, whether it succeeds or fails. This makes sure cleanup tasks are done.Last-In, First-Out Execution: Deferred functions in both Go and
with-defer.jsrun in reverse/LIFO(Last-In, First-Out) order, meaning the last function added runs first. This helps with cleaning up resources in the correct order.User-Friendly API: The
defer()inwith-defer.jsis similar to Go’s, making it easy to use for scheduling functions in JavaScript.
Same vibe, right?
Features
- Stack up deferred functions to run after your main code.
- Set timeouts and cancel deferred tasks.
- Built-in error reporting with optional error throwing.
- Optional debug mode for the curious souls.
- Full TypeScript support with complete type definitions.
- Production ready with comprehensive input validation.
- Well tested with extensive edge case coverage.
Install
npm
npm install @dacodedbeat/with-defer-jsDeno
import { withDefer } from 'npm:@dacodedbeat/with-defer-js';Bun
bun add @dacodedbeat/with-defer-jsUsage
Wrap your function with withDefer and use defer to schedule tasks.
import { withDefer } from '@dacodedbeat/with-defer-js';
const mainFunction = async (defer) => {
defer(() => console.log('Deferred task!'), { timeout: 5000 });
console.log('Doing main stuff!');
};
withDefer(mainFunction)();TypeScript Usage
import { withDefer, type DeferFunction } from '@dacodedbeat/with-defer-js';
const mainFunction = async (defer: DeferFunction) => {
defer(() => console.log('Cleanup complete!'));
// Your main logic here
return 'Success!';
};
await withDefer(mainFunction)();Options
[!IMPORTANT] When implementing, please verify this with the your installed version of the source code, as this is can change over time.
Set options when you wrap your function, as well as on each deferred callback:
| Option | Type | Default | Description |
|-----------------|------------|---------|----------------------------------------------|
| timeout | number | null | Max time (ms) for deferred functions. |
| debug | boolean | false | Debug mode. |
| throwOnError | boolean | false | Throw error if a deferred function fails. |
| errorReporter | function | null | Custom error handler for deferred functions. |
Error Handling & Debugging
- Use
throwOnErrorto fail hard if a deferred function crashes. - Use
errorReporterfor custom error handling. - Enable
debugto get logs.
Cancel a Deferred Task
const { cancel } = defer(() => console.log('This won't run if canceled.'));
cancel();Execution Guarantees
Return Value Capture
Your main function's return value is captured and available when withDefer() resolves:
const example = withDefer(async (defer) => {
defer(() => console.log('cleanup'));
return { userId: 123 };
});
const result = await example();
// result === { userId: 123 }
// Cleanup has already executedExecution Order
Deferreds execute in LIFO (Last-In-First-Out) order, matching Go's defer semantics:
const example = withDefer(async (defer) => {
defer(() => console.log('3. First registered'));
defer(() => console.log('2. Second registered'));
defer(() => console.log('1. Third registered'));
});
await example();
// Output:
// 1. Third registered
// 2. Second registered
// 3. First registeredError Handling
When errors occur in deferred functions:
- Debug logging (if enabled)
- Error reporter callback (if provided)
- Error aggregation and optional throwing
Errors don't mutate original error objects; use .cause property to access the original error:
try {
await example();
} catch (aggErr) {
if (aggErr instanceof AggregateError) {
const wrappedErr = aggErr.errors[0];
const originalErr = wrappedErr.cause; // Original error preserved
}
}Timeout Precision
Timeouts are implemented with setTimeout(), which has platform-dependent precision:
- Node.js: ±1-5ms typical
- Browser: ±1-10ms typical
- Electron: ±5-15ms typical
Timeouts are properly cleaned up after completion and never fire before the specified interval.
Important Limitation: Fire-and-Forget Async Operations
If a deferred callback returns a promise that rejects after the deferred execution phase completes, the rejection is not caught:
// ❌ BAD: Unhandled promise rejection
defer(() => {
setTimeout(() => Promise.reject(new Error('late error')), 100);
});
// ✅ GOOD: Await all async operations
defer(async () => {
await fetch('/cleanup');
});
// ✅ GOOD: Explicitly handle unhandled rejections
defer(() => {
fetch('/cleanup').catch(err => console.error('failed:', err));
});Concurrency
Multiple withDefer() calls are independent and don't interfere with each other:
const [result1, result2] = await Promise.all([
withDefer(async (defer) => {
defer(() => db.close());
return 'db cleaned';
})(),
withDefer(async (defer) => {
defer(() => server.close());
return 'server cleaned';
})()
]);
// Both execute in parallel, independentlyBreaking Changes (v0.0.3)
This release makes with-defer.js truly concurrent-safe and Go-compatible:
- Isolated defer stacks per invocation: Each call to
withDefer(fn)()now gets its own independent defer queue, preventing interference between concurrent calls - Sequential LIFO execution: Deferreds now execute sequentially in LIFO order instead of concurrently, matching Go's semantics
- No nested defer calls: Calling
defer()during deferred execution now throws an error instead of silently failing
Migration: If your code relied on concurrent deferred execution, you'll need to adjust expectations. Deferreds now execute strictly in order, one at a time, in LIFO (Last-In-First-Out) order - just like Go.
Contributing
If you'd like to contribute to with-defer.js, we welcome your input! Please read
our Contributing Guidelines to get started.
License
with-defer.js is licensed under the Mozilla Public License 2.0. See the
LICENSE file for more details.
