Skip to content

Conversation

@Harris-Miller
Copy link

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

@changeset-bot
Copy link

changeset-bot bot commented Oct 3, 2025

⚠️ No Changeset found

Latest commit: da73f3d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feat request: fromAsync to interop with async functions more easily

1 participant