result icon indicating copy to clipboard operation
result copied to clipboard

Question: How would I chain async functions?

Open iflp opened this issue 6 years ago • 1 comments

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>'.

iflp avatar Nov 10 '19 05:11 iflp

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 avatar Nov 28 '19 12:11 jviide

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 🙂

jviide avatar Oct 19 '22 13:10 jviide