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

go-result-js

v1.0.5

Published

go-like results

Downloads

483

Readme

NPM Version Coverage

go-result-js

Go-like results:

const [ err, result ] = foo();
  • Zero dependencies
  • Full typescript support
  • 100% test coverage

Usage

Install:

npm i go-result-js

Import:

import { ResultA, ResultErr, ResultOk } from 'go-result-js';

Or use it globally:
(write in main file, before everythink)

import 'go-result-js/lib/global';

Example with exceptions

Before:

const result = await doSmthWithException();
// (node:17320) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Request failed with status code 400
// (node:17320) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

After:

const [ err, result ] = await ResultA(doSmthWithException());
if (err || !result) {
    // exception handled!
}

Example

function divide(a: number, b: number): Result<number> {
    if (b === 0) return ResultErr('Can not divide by zero!');
    return ResultOk(a / b);
}

function main() {
    const [ err, result ] = divide(10, 5);

    if (err) console.error(err);
    else console.log('success', result);
}

Example with async

const asyncDivide = (a: number, b: number): ResultA<number> => ResultA<number>(resolve => {
    resolve(b === 0 ? new Error('Can not divide by zero!') : a / b);
});

async function asyncMain() {
    const [ err, result ] = await asyncDivide(10, 5);

    if (err) console.error(err);
    else console.log('success', result);
}

Example with AWS

import { Auth } from 'aws-amplify';

export async function main() {
    const [ err, user ] = await ResultA(Auth.signIn('root', 'password'));
}

Multiple results

Handle multiple ResultA results, and catch any errors.

const { err, values } = await resultAll(
    Content.fetchById(contentType, id),
    Rubrics.fetchRubrics(),
    ContentTypes.fetchContentTypes(),
);

if (err) {
    // on any error
}

const {
    0: content,
    1: rubrics,
    2: contentTypes,
} = values;

API

export type ResultErr<ErrorT extends Error = Error> = ErrorT|true|undefined;
export type Result<T, ErrorT extends Error = Error> = [ ResultErr<ErrorT>, T|undefined ];
export type ResultA<T, ErrorT extends Error = Error> = Promise<Result<T, ErrorT>>;
function registerGlobally(global?: any): Result<boolean>

Assign all methods to global object.
go-result-js/lib/global calls it.

function ResultOk<T>(value: T): Result<T>

Returns value with undefined error.

function ResultErr<ErrorT extends Error, T=any>(err: ErrorT|true|string = true): Result<T, ErrorT>

Returns error with undefined value.

function ResultA<T, ErrorT extends Error>(
    x: Promise<T> | ((
        resolve: (value: undefined|T|Error) => void,
        reject: (err?: ErrorT) => void
    ) => void)
): ResultA<T, ErrorT>

Takes Promise's callbacks or Promise, catch it's error and resolve as Promise<Result>.

function resultAll<Results extends ResultA<any>[]>(
    ...results: Results
): Promise<{
    err: ResultErr | undefined,
    values: {
        [i in keyof Results]: PickSecondItem<PromiseType<Results[i]>, undefined>
    },
    results: {
        [i in keyof Results]: PromiseType<Results[i]>
    }
}>