Skip to content

Wrap async/sync result in the library #111

@keogami

Description

@keogami

Its super common for async/sync operations to throw an error, but i don't see a constructor to conveniently wrap the operation in the Result. I propose a new constructor:

async function AsyncResultOf<T>(val: Promise<T>): Promise<Result<T, Error>> {
  try {
    return Ok(await val);
  } catch(err) {
    return Err(err);
  }
}

This allows us to go from the throw/catch error handling to the monadic error handling patterns const result = await AsyncResultOf(fetch(...))

I will go further to suggest an even more general constructor that translates both async and non-async fallible operations:

async function ResultOf<T>(val: () => Promise<T>): Promise<Result<T, Error>> {
  try {
    return Ok(await val());
  } catch(err) {
    return Err(err);
  }
}

This can of course be overloaded with the signature of AsyncResultOf.

(PS im trying to whip up a PR but the test keeps saying "Timed out while running tests" on my machine)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions