npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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.

Readme

with-defer.js

npm version License: MPL 2.0 Formatted with Biome

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

  1. Automatic Execution After Function Ends: Just like in Go, functions in with-defer.js run after the main function finishes, whether it succeeds or fails. This makes sure cleanup tasks are done.

  2. Last-In, First-Out Execution: Deferred functions in both Go and with-defer.js run 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.

  3. User-Friendly API: The defer() in with-defer.js is 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-js

Deno

import { withDefer } from 'npm:@dacodedbeat/with-defer-js';

Bun

bun add @dacodedbeat/with-defer-js

Usage

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 throwOnError to fail hard if a deferred function crashes.
  • Use errorReporter for custom error handling.
  • Enable debug to 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 executed

Execution 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 registered

Error Handling

When errors occur in deferred functions:

  1. Debug logging (if enabled)
  2. Error reporter callback (if provided)
  3. 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, independently

Breaking 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.