-
-
Notifications
You must be signed in to change notification settings - Fork 36
Open
Description
Its super common for async/sync operations to throw an error, but i don't see a constructor to conveniently wrap the operation in the Result. I propose a new constructor:
async function AsyncResultOf<T>(val: Promise<T>): Promise<Result<T, Error>> {
try {
return Ok(await val);
} catch(err) {
return Err(err);
}
}This allows us to go from the throw/catch error handling to the monadic error handling patterns const result = await AsyncResultOf(fetch(...))
I will go further to suggest an even more general constructor that translates both async and non-async fallible operations:
async function ResultOf<T>(val: () => Promise<T>): Promise<Result<T, Error>> {
try {
return Ok(await val());
} catch(err) {
return Err(err);
}
}This can of course be overloaded with the signature of AsyncResultOf.
(PS im trying to whip up a PR but the test keeps saying "Timed out while running tests" on my machine)
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels