JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 277
  • Score
    100M100P100Q96085F
  • License MIT

go-like results

Package Exports

  • go-result-js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (go-result-js) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

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 { Result, ResultErr, ResultOk } from 'go-result-js';

Or use it globally in js:

require('go-result-js').registerGlobally();

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';
import { ResultA } from './index';

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

API

Types
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>>;
Methods
function registerGlobally(global?: any): Result<boolean>

Assign all methods to global object.

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

Returns value with undefined error.

function ResultErr<T, ErrorT extends Error>(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>.