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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@kawaz/provide-defer

v2.0.0

Published

A utility library that provides a mechanism for deferring the execution of functions or Promises, similar to Go's defer statement.

Downloads

31

Readme

npm version

@kawaz/provide-defer

@kawaz/provide-defer is a TypeScript utility package that provides a mechanism for deferring the execution of functions or Promises, similar to Go's defer statement. It allows you to schedule cleanup or finalization code to run after the main function has completed, regardless of whether it completes normally or throws an error.

Features

  • Defer execution of functions or Promises
  • Execute deferred functions in reverse order (LIFO)
  • Options for error handling and asynchronous execution
  • Aggregates errors from main and deferred functions
  • TypeScript support with generic typing

Installation

npm install @kawaz/provide-defer

Usage

Here's a basic example of how to use provideDefer:

import { provideDefer } from '@kawaz/provide-defer';

const result = await provideDefer(async (defer) => {
  const resource = await acquireResource();
  defer(() => releaseResource(resource));

  // Use the resource...
  return someOperation(resource);
});

API

provideDefer<T>(fn: (defer: DeferFunction) => T | Promise<T>): Promise<T>

  • fn: The main function to execute. It receives a defer function as an argument.
  • Returns a Promise that resolves with the result of the main function.

DeferFunction

type DeferFunction = (fn: FunctionOrPromise<unknown>, options?: DeferOptions) => void
  • fn: The function or Promise to be deferred.
  • options: Optional settings to control the behavior of the deferred function.

DeferOptions

type DeferOptions = {
  noThrow?: boolean;
  noWait?: boolean;
}
  • noThrow: If true, errors from this deferred function will be ignored.
  • noWait: If true, the execution of the deferred function will start as scheduled, but provideDefer will not wait for its completion before resolving. This allows the deferred function to run in the background.

Error Handling

If any errors occur in the deferred functions (and noThrow is not set), or if the main function throws an error, provideDefer will throw an AggregateError containing all the errors.

Examples

Basic Usage

import { provideDefer } from '@kawaz/provide-defer';

const result = await provideDefer((defer) => {
  defer(() => console.log('This will be executed last'));
  defer(() => console.log('This will be executed second'));
  console.log('This will be executed first');
  return 'Main function result';
});

console.log(result);
// Outputs:
// This will be executed first
// This will be executed second
// This will be executed last
// Main function result

Error Handling

import { provideDefer } from '@kawaz/provide-defer';

try {
  await provideDefer((defer) => {
    defer(() => { throw new Error('Deferred error 1'); });
    defer(() => { throw new Error('Deferred error 2'); });
    throw new Error('Primary error');
  });
} catch (error) {
  if (error instanceof AggregateError) {
    console.log(error.message); // Outputs: 'Main error: "Primary error". Additionally, 2 deferred error(s) occurred.'
    console.log(error.errors);
    // Array of all errors: The main error is the first element, followed by deferred errors
    // [
    //   Error: Primary error,
    //   Error: Deferred error 2,
    //   Error: Deferred error 1
    // ]
  }
}

Using noThrow and noWait Options

import { provideDefer } from '@kawaz/provide-defer';

await provideDefer((defer) => {
  defer(() => { throw new Error('This error will be ignored'); }, { noThrow: true });

  defer(async () => {
    console.log('Start of long-running operation');
    await new Promise(resolve => setTimeout(resolve, 5000));
    console.log('End of long-running operation');
  }, { noWait: true });

  console.log('Main function continues immediately');
  return 'Main function result';
});

console.log('provideDefer resolved');

// Output:
// Start of long-running operation
// Main function continues immediately
// provideDefer resolved
// End of long-running operation (after about 5 seconds)

License

MIT

Author

Yoshiaki Kawazu

Contributing

Contributions, issues, and feature requests are welcome! Feel free to check issues page.

Support

If you like this project, please consider supporting it by giving a ⭐️ on GitHub!