I created a lightweight, multi-paradigm, zero dependency, `Result`-style library in JS.

Introducing a Lightweight, Multi-Paradigm Result Handling Library for JavaScript

Managing success and error states consistently across asynchronous operations can be challenging in JavaScript. To address this, I have developed a minimalist, zero-dependency library that offers a flexible, Result-style approach for handling outcomes in various programming paradigms.

Versatile Support for Different Coding Styles

This library is designed to seamlessly integrate into your existing workflow, whether you prefer array destructuring, object destructuring, functional programming, or object-oriented patterns.

Array/Tuple Destructuring

javascript
const [value, error] = await attempt(someFunction, ...args);

Object Destructuring

javascript
const { value, error } = await attempt(someFunction, ...args);

Functional Style with Guards

“`javascript
const result = await attempt(someFunction, …args);

if (succeeded(result)) {
const value = getResultValue(result);
// Proceed with success logic
} else if (failed(result)) {
const error = getResultError(result);
// Handle failure
}
“`

Object-Oriented Pattern

“`javascript
const result = await attempt(someFunction, …args);

if (result instanceof AttemptResult) {
// Access success value via result.value
} else if (result instanceof AttemptFailure) {
// Access error via result.error
}
“`

Creating Safe, Resilient Functions

You can easily wrap potentially unsafe functions, turning them into safe, reliable versions:

javascript
const safeFunction = createSafeCallback(dangerousFunction);
const result = await safeFunction('some', 'args');

Composing Safe Operations

Chain multiple asynchronous tasks with ease, handling errors gracefully:

javascript
const result = await attemptAll(
() => import('@scope/http-lib'),
({ get }) => get('https://api.example.com/users'),
users => {
// Process retrieved users
}
);

About the Library

  • Name: @aegisjsproject/attempt
  • Size: Approximately 1.1 KB after minification and gzipping, before tree-shaking
  • Dependencies: None
  • Test Coverage: 100%

This library empowers developers to write cleaner, more reliable asynchronous code by standardizing result handling across various paradigms without introducing complexity or bloat.

Find Out More and Get


Leave a Reply

Your email address will not be published. Required fields are marked *