API reference / @evolu/common / Task / toTask

Function: toTask()

function toTask<T, E>(fn): Task<T, E>;

Defined in: packages/common/src/Task.ts:265

Converts async function returning Result to a Task.

Example

interface FetchError {
  readonly type: "FetchError";
  readonly error: unknown;
}

// Task version of fetch with proper error handling and cancellation support.
const fetch = (url: string) =>
  toTask((context) =>
    tryAsync(
      () => globalThis.fetch(url, { signal: context?.signal ?? null }),
      (error): FetchError => ({ type: "FetchError", error }),
    ),
  );

// `satisfies` shows the expected type signature.
fetch satisfies (url: string) => Task<Response, FetchError>;

const result1 = await fetch("https://api.example.com/data")();
result1 satisfies Result<Response, FetchError>;

// With AbortController
const controller = new AbortController();
const result2 = await fetch("https://api.example.com/data")(controller);
result2 satisfies Result<Response, FetchError | AbortError>;

Type Parameters

Type Parameter
T
E

Parameters

ParameterType
fn(context?) => Promise<Result<T, E>>

Returns

Task<T, E>

Was this page helpful?