Options
All
  • Public
  • Public/Protected
  • All
Menu

result-async

Index

Type aliases

Result

Result<OkData, ErrorMessage>: OkResult<OkData> | ErrorResult<ErrorMessage>

Represents the result of an operation that could succeed or fail.

Type parameters

  • OkData

  • ErrorMessage

ResultP

ResultP<OkData, ErrorMessage>: Promise<Result<OkData, ErrorMessage>>

A Result, wrapped in a promise. The promise should never be rejected, and should always resolve to an Ok or Error.

Type parameters

  • OkData

  • ErrorMessage

Variables

Const ResultP

ResultP: PromiseConstructor = Promise

Functions

allOk

  • allOk<OkData, ErrorMessage>(results: Result<OkData, ErrorMessage>[]): Result<OkData[], ErrorMessage>
  • For checking that a collection of computations all succeeded. Similar to Promise.all for Results.

    Takes a list of Results. If all are Ok, collects the data in a list and returns ok([data]). If any are Errors, returns the first error(msg)

    Type parameters

    • OkData

    • ErrorMessage

    Parameters

    • results: Result<OkData, ErrorMessage>[]
      allOk([ok(1), ok(2), ok(3)]) // ok([1, 2, 3])
      
      allOk([ok(1), error(2), error(3)]) // error(2)

    Returns Result<OkData[], ErrorMessage>

allOkAsync

  • allOkAsync<OkData, ErrorMessage>(promises: ResultP<OkData, ErrorMessage>[]): ResultP<OkData[], ErrorMessage>
  • For checking that a collection async computations all succeeded. Promise.all for Results wrapped in promises.

    Takes a list of Promises. If all are Ok, collects the data in a list and returns ok([data]). If any are any promise OR result errors, returns the first error(msg)

    function countComments(postId) {
      return pipeA
        (fetchAllComments(postId)),
        (allOkAsync),
        (okThen(comments => comments.length))
        (errorReplace("some comments didn't load"))
    }

    Type parameters

    • OkData

    • ErrorMessage

    Parameters

    • promises: ResultP<OkData, ErrorMessage>[]

    Returns ResultP<OkData[], ErrorMessage>

attempt

  • attempt<OkData, ErrorMessage>(action: function, opts?: object): Result<OkData, ErrorMessage>
  • Call an action that could throw an error, and return a Result. Successful actions will be wrapped in an ok For predictable errors, you should provide a static or dynamic error handler

    Type parameters

    • OkData

    • ErrorMessage

    Parameters

    • action: function

      The unsafe action to perform

        • (): OkData
        • Returns OkData

    • Default value opts: object = {}

    Returns Result<OkData, ErrorMessage>

either

  • either<OkData, ErrorMessage, OkOutput, ErrorOutput>(result: Result<OkData, ErrorMessage>, onOk: function, onError: function): OkOutput | ErrorOutput
  • Takes a result, and runs either an onOk or onError function on it.

    Type parameters

    • OkData

    • ErrorMessage

    • OkOutput

    • ErrorOutput

    Parameters

    • result: Result<OkData, ErrorMessage>

      Result to match against

    • onOk: function

      Function to run if the result is an Ok

        • (ok: OkData): OkOutput
        • Parameters

          • ok: OkData

          Returns OkOutput

    • onError: function

      Function to run if the result is an Error

        • (error: ErrorMessage): ErrorOutput
        • Parameters

          • error: ErrorMessage

          Returns ErrorOutput

    Returns OkOutput | ErrorOutput

    The return value of the function that gets run.

    // Use `either` to unwrap a Result.
    const userId = either(
      await fetchAUser(),
      user => user.id,
      () => null
    )
    
    // Use `either` to act on both cases, but leave wrapped.
    const userId = either(
      await fetchAUser(),
      user => ok(user.id),
      () => error("not found")
    )

Const error

  • error<T>(message: T): ErrorResult<T>
  • Wraps a message in an Error.

    Type parameters

    • T

    Parameters

    • message: T

    Returns ErrorResult<T>

errorDo

  • errorDo<OkData, ErrorMessage>(f: function): (Anonymous function)
  • Runs a function for side effects on the payload, only if the result is Error.

    Type parameters

    • OkData

    • ErrorMessage

    Parameters

    • f: function

      the function to run on the error message

        • (ok: ErrorMessage): any
        • Parameters

          • ok: ErrorMessage

          Returns any

    Returns (Anonymous function)

    The original result

    const result = fetchData();
    // Log an error if the fetch failed.
    errorDo(console.error)(result);

errorDoAsync

  • errorDoAsync<ErrorMessage>(f: function): (Anonymous function)
  • Runs a function for side effects on the payload, only if the result is Error. Waits for the side effect to complete before returning.

    Type parameters

    • ErrorMessage

    Parameters

    • f: function

      the function to run on the error message

        • (ok: ErrorMessage): any
        • Parameters

          • ok: ErrorMessage

          Returns any

    Returns (Anonymous function)

    a promise of the original Result

    pipeA(
      (fetchData)
      // Logs an error, and awaits completion before moving on.
      (errorDoAsync(logError))
      (okThen(transformData))

errorOrThrow

  • errorOrThrow<ErrorMessage>(result: Result<any, ErrorMessage>): ErrorMessage
  • Get the error message from a result. If it's an Ok instead, throw an error.

    Type parameters

    • ErrorMessage

    Parameters

    • result: Result<any, ErrorMessage>

    Returns ErrorMessage

    the error message

    errorOrThrow(error("bad"));
    // "bad"
    
    errorOrThrow(ok("good"));
    // throws new Error("good")

errorReplace

  • errorReplace<ErrorOutput>(newError: ErrorOutput): (Anonymous function)
  • Replaces a message that's wrapped in an error(message) Useful if you don't care about the old message, just the fact that previous call failed.

    Takes a Result and a mapping function. If the result is an Error, applies the function to the message. If the result is an Ok, passes the Result through unchanged.

    Type parameters

    • ErrorOutput

    Parameters

    • newError: ErrorOutput

    Returns (Anonymous function)

errorRescue

  • errorRescue<ErrorMessage, OkOutput, ErrorOutput>(f: function): (Anonymous function)
  • Attempts to rescue failed results. Passes successful ones through.

    Takes a mapping function, then a result. If the result is an Error, applies the function to the data. If the result is an Ok, passes the Result through unchanged.

    The return value must itself be a result, which will be returned.

    Type parameters

    • ErrorMessage

    • OkOutput

    • ErrorOutput

    Parameters

    • f: function

      the function to run on the error data

        • (ok: ErrorMessage): Result<OkOutput, ErrorOutput>
        • Parameters

          • ok: ErrorMessage

          Returns Result<OkOutput, ErrorOutput>

    Returns (Anonymous function)

    • The Result from function f or the Ok result
    const rescueNotFound = errorThen(errorMessage =>
      errorMessage === "not found" ? ok("unknown") : error(errorMessage)
    );
    
    rescueNotFound(ok("alice")) // ok("alice")
    rescueNotFound(error("not found")) // ok("unknown")
    rescueNotFound(error("network error")) // error("network error")

errorRescueAsync

  • errorRescueAsync<ErrorMessage, OkOutput, ErrorOutput>(f: function): (Anonymous function)
  • Chains together async operations that may succeed or fail

    Takes a Result and a mapping function. If the result is an Error, applies the function to the data and returns the new promise-wrapped result. If the result is an Ok, passes the Result through unchanged.

    Type parameters

    • ErrorMessage

    • OkOutput

    • ErrorOutput

    Parameters

    • f: function

      the function to run on the error message

        • (ok: ErrorMessage): ResultP<OkOutput, ErrorOutput>
        • Parameters

          • ok: ErrorMessage

          Returns ResultP<OkOutput, ErrorOutput>

    Returns (Anonymous function)

    • The Result from function f or the Ok result
    const fetchData = () => fetch("https://example.com/data");
    pipeA
      (getCachedData)
      (errorRescueAsync(fetchData))
      (okThen(transformData))
      .value

errorThen

  • errorThen<ErrorMessage, ErrorOutput>(f: function): (Anonymous function)
  • Transforms a failed result, and passes through a successful result.

    Takes a mapping function, then a result. If the result is an Error, applies the function to the data. If the result is an Ok, passes the Result through unchanged.

    Wraps the output of the function in an Error.

    Type parameters

    • ErrorMessage

    • ErrorOutput

    Parameters

    • f: function

      the function to run on the error data

        • (error: ErrorMessage): ErrorOutput
        • Parameters

          • error: ErrorMessage

          Returns ErrorOutput

    Returns (Anonymous function)

    • The Result from function f or the Ok result
    const normalizeErrorCase = errorThen(message =>
      message.toLowerCase()
    )
    
    normalizeErrorCase(ok("alice")) // ok("alice")
    normalizeErrorCase(error("NOT FOUND")) // error("not found")

firstOk

  • firstOk<OkData>(results: Result<OkData, any>[]): Result<OkData, null>
  • Find and return the first ok(data) in the collection. If there are no Ok values, return error(null)

    allOk([error(1), error(2), ok(3), ok(4)]) // ok(3)
    allOk([error(1), error(2)]) // error(null)

    Type parameters

    • OkData

    Parameters

    • results: Result<OkData, any>[]

    Returns Result<OkData, null>

isError

  • isError(result: Result<any, any>): boolean
  • Type guard to check if a Result is an Error

    Parameters

    • result: Result<any, any>

      The result to check

      const result = error("not found");
      
      if (isError(result)) {
        result.error // exists
      }

    Returns boolean

isOk

  • isOk(result: Result<any, any>): boolean
  • Type guard to check if a Result is Ok

    Parameters

    • result: Result<any, any>

      The result to check

      const result = ok(1);
      
      if (isOk(result)) {
        result.ok // exists
      }

    Returns boolean

Const isResult

  • isResult(result: Result<any, any> | any): boolean
  • Type guard to check if an object is a Result.

    Parameters

    • result: Result<any, any> | any

      The object to check

      const result = ;
      
      isResult(error("not found")) // true

    Returns boolean

Const ok

  • ok<T>(data: T): OkResult<T>
  • Wraps data in an Ok.

    Type parameters

    • T

    Parameters

    • data: T

      The success payload

      ok(1)

    Returns OkResult<T>

okChain

  • okChain<OkData, OkOutput, ErrorOutput>(f: function): (Anonymous function)
  • Performs an operation that could succeed or fail on a successful result Passes through a failed result.

    Takes a mapping function, then a result. If the result is an Ok, applies the function to the data. If the result is an Error, passes the Result through unchanged.

    The return value must itself be a result, which will be returned.

    Type parameters

    • OkData

    • OkOutput

    • ErrorOutput

    Parameters

    • f: function

      the function to run on the ok data

        • (ok: OkData): Result<OkOutput, ErrorOutput>
        • Parameters

          • ok: OkData

          Returns Result<OkOutput, ErrorOutput>

    Returns (Anonymous function)

    • The Result from function f or the Error

okChainAsync

  • okChainAsync<OkData, OkOutput, ErrorOutput>(f: function): (Anonymous function)
  • Chains together async operations that may succeed or fail

    Takes a Result and a mapping function. If the result is an Ok, applies the function to the data. If the result is an Error, passes the Result through unchanged.

    Type parameters

    • OkData

    • OkOutput

    • ErrorOutput

    Parameters

    • f: function

      the function to run on the ok data

        • (ok: OkData): ResultP<OkOutput, ErrorOutput>
        • Parameters

          • ok: OkData

          Returns ResultP<OkOutput, ErrorOutput>

    Returns (Anonymous function)

    • The Result from function f or the Error
    pipeA
      (fetchUser())
      (okChainAsync(user => fetchComments(user.id)))
      (okDo(comments => console.log('total comments:', comments.length))
      .value

okDo

  • okDo<OkData, ErrorMessage>(f: function): (Anonymous function)
  • Runs a function for side effects on the payload, only if the result is Ok.

    Type parameters

    • OkData

    • ErrorMessage

    Parameters

    • f: function

      the function to run on the ok data

        • (ok: OkData): any
        • Parameters

          • ok: OkData

          Returns any

    Returns (Anonymous function)

    The original result

    const result = fetchData();
    // Log the data if the fetch succeeded.
    okDo(console.log);

okDoAsync

  • okDoAsync<OkData>(f: function): (Anonymous function)
  • Runs a function for side effects on the payload, only if the result is Ok.

    Type parameters

    • OkData

    Parameters

    • f: function

      the async function to run on the ok data

        • (ok: OkData): any
        • Parameters

          • ok: OkData

          Returns any

    Returns (Anonymous function)

    A promise of the the original result

    pipeA(
      (fetchData)
      // Saves to cache, and awaits completion before moving on.
      (okDoAsync(saveToCache))
      (okThen(transformData))

okOrThrow

  • okOrThrow<OkData>(result: Result<OkData, any>): OkData
  • Get the error message from a result. If it's an Ok, throw an error.

    Type parameters

    • OkData

    Parameters

    Returns OkData

    the ok data

    const okResult = ok("good");
    okOrThrow(result);
    // "good"
    const errorResult = error("bad");
    okOrThrow(result);
    // throws new Error("bad")

okReplace

  • okReplace<OkOutput>(newData: OkOutput): (Anonymous function)
  • Replaces a value that's wrapped in an {ok: data} Useful if you don't care about the data, just the fact that previous call succeeded.

    Takes a Result and a mapping function. If the result is an Error, applies the function to the message. If the result is an Ok, passes the Result through unchanged.

    It wraps the return value in an {error: new_message}.

    Type parameters

    • OkOutput

    Parameters

    • newData: OkOutput

    Returns (Anonymous function)

okThen

  • okThen<OkData, OkOutput>(f: function): (Anonymous function)
  • Transforms a successful result, and passes through a failed result.

    Takes a mapping function, then a result. If the result is an Ok, applies the function to the data. If the result is an Error, passes the Result through unchanged.

    Wraps the output of the function in an Ok.

    Type parameters

    • OkData

    • OkOutput

    Parameters

    • f: function

      the function to run on the ok data

        • (ok: OkData): OkOutput
        • Parameters

          • ok: OkData

          Returns OkOutput

    Returns (Anonymous function)

parseJson

  • parseJson<T, ErrorMessage>(json: string, opts?: object): Result<T, ErrorMessage>
  • Safely parse JSON

    Type parameters

    • T

    • ErrorMessage

    Parameters

    • json: string

      Stringified JSON to parse

    • Default value opts: object = {}

    Returns Result<T, ErrorMessage>

promiseToResult

  • promiseToResult<OkData>(promise: Promise<OkData>): ResultP<OkData, any>
  • Awaits a promise, and returns a result based on the outcome

    Note that the Error case isn't typesafe, since promises don't have an error type, just a success one. It's probably a good idea to use a errorThen or errorReplace to handle errors and soon as possible.

    Type parameters

    • OkData

    Parameters

    • promise: Promise<OkData>

    Returns ResultP<OkData, any>

    Ok if the promise resolved, Error if it was rejected.

    pipeA(
      (promiseToResult(fetch("http://example.com/data")))
      (errorThen(handleError))
      (okThen(transformData))

resultToBoolean

  • resultToBoolean(result: Result<any, any>): boolean
  • Converts a result to a boolean.

    Parameters

    Returns boolean

    true if Ok, false if Error

    resultToBoolean(ok(1)) // true
    resultToBoolean(error(1)) // false

resultify

  • resultify<Args, OkData>(f: function): (Anonymous function)
  • Converts a function that returns a promise to one that always resolved to a Result

    Note that the Error case isn't typesafe, since promises don't have an error type, just a success one. It's probably a good idea to use a errorThen or errorReplace to handle errors and soon as possible.

    Type parameters

    • Args: any[]

    • OkData

    Parameters

    • f: function

      A function that returns a promise

        • (...args: Args): Promise<OkData>
        • Parameters

          • Rest ...args: Args

          Returns Promise<OkData>

    Returns (Anonymous function)

    a function that returns a promise that always resolves to a Result

    const writeFile = resultify(promisify(fs.writeFile));
    
    pipeA(
      (writeFile("path/to/file"))
      (errorThen(handleError))
      (okThen(transformFileData))
    )

Generated using TypeDoc