neverthrow icon indicating copy to clipboard operation
neverthrow copied to clipboard

New: ResultAsync.fromPromiseResult static method

Open Harris-Miller opened this issue 2 months ago • 1 comments

Closes #608

It's not uncommon to write an async function with serial await because the second call depends on the first, where you're try/catch handlers return ok() or err() respectively. The return type is Promise<Result<T, E>>, but you desire it to be ResultAsync<T, E>.

The ResultAsync.fromPromiseResult static method wraps a Promise<Result<T, E>> returning function, returning a function with the same arguments, and returning the desired ResultAsync<T, E>.

Also available as a standalone function import { fromPromiseResult } from 'neverthrow'

Example:

export const callApi: ResultAsync<Person[], Error> = ResultAsync.fromPromiseResult(async (postId: number): Promise<Result<Person[], Error>> => {
  try {
    const post = await fetch(`/api/posts/${id}`).then(resp => !resp.ok ? Promise.reject(resp) : resp);
    const query = post.comments.map(c => c.commenterId).join(',');
    const people = await fetch(`/api/people?ids=${query}`).then(resp => !resp.ok ? Promise.reject(resp) : resp);
    return ok(people);
  } catch(e) {
    return err(e as Error);
  }
});

const people: Person[] = await callApi(123)
  .orElse(e => {
    console.error(e);
    return [];
  });

The Method Name:

As the saying goes, naming things is hard. fromPromiseResult is just what I came up with for this function. There is probably a better one out there. I'm very open to suggestions

Harris-Miller avatar Oct 03 '25 06:10 Harris-Miller