Question: How would I chain async functions?
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>'.
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 🙂
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 🙂