badrap / result

A TypeScript result type taking cues from Rust's Result and Haskell's Either types
MIT License
292 stars 6 forks source link

Question: How would I chain async functions? #2

Closed iflp closed 2 years ago

iflp commented 4 years ago

I'm trying to chain an async function, and am getting a type error. Can anyone point me in the right direction?

const fooRes: Result<string, Error> = await foo();
const barRes = fooRes.chain(async e => await bar(e)).unwrap(); 
Argument of type 'e => Promise<Result<string, Error>>' is not assignable to parameter of type '(value: string) => Result<unknown, Error>'.
jviide commented 4 years ago

The problem arises from the fact that chain(a) expects a to return a Result. In this case async e => await bar(e) returns a Promise (like async functions always do). You might want to flip the logic around by using map:

fooRes.map(async e => await bar(e)).unwrap();

The return value has the type Result<Promise<string>, Error>, so you'd probably want to await it to get the string:

const barRes = await fooRes.map(e => await bar(e)).unwrap();

As a further simplification you can combine the map and the unwrap:

const barRes = await fooRes.unwrap(async e => await bar(e));

Hope this helps 🙂

jviide commented 2 years ago

This issue has not seen activity for a while, so I'll close this. Feel free to reopen it (or a new issue) if the need arises 🙂