Skip to main content

runAsync

@ts-rust/std


@ts-rust/std / Result / runAsync

Function: runAsync()

function runAsync<T, E>(action, mkErr): PendingResult<T, E>;

Defined in: packages/std/src/result/result.ts:218

Executes an asynchronous action and wraps the outcome in a PendingResult, handling errors with a custom error mapper.

The runAsync function attempts to execute the provided action function, which returns a value of type Promise<T>. If the action succeeds, it returns a PendingResult that resolves to Ok variant containing the value. If the action fails (throws an error), the error is passed to the mkErr function to create an error of type E, which is then wrapped in an Err variant.

This function is useful for safely executing operations that might fail, ensuring errors are handled in a type-safe way using the Result type.

Type Parameters

Type Parameter

T

E

Parameters

ParameterTypeDescription

action

() => Promise<T>

A function that performs the operation, returning a Promise resolving to T.

mkErr

(error) => Awaited<E>

A function that converts an error (of type unknown) into an error of type E.

Returns

PendingResult<T, E>

A PendingResult<T, E> that resolves to either a value (Ok<T>) or the mapped error (Err<E>).

Example

import { run, PendingResult, Result } from "@ts-rust/std";

const pendingRes: PendingResult<string, Error> = runAsync(
(): Promise<string> =>
fetch("https://api.example.com/text").then((res) => res.text()),
(e) => new Error(`Fetch failed: ${JSON.stringify(e)}`),
);

const res: Result<string, Error> = await pendingRes;

if (res.isErr()) {
console.log(res.unwrapErr().message); // Fetch failed: ...
}