Skip to content

feat: add asyncAttempt function #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# These are supported funding model platforms

github: [lambdalisue] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
github: [
lambdalisue,
] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
Expand Down
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ assertThrows(
import { assertEquals } from "@std/assert";
import { attempt } from "@core/errorutil/attempt";

assertEquals(attempt(() => 42), [undefined, 42]);
assertEquals(
attempt(() => 42),
[undefined, 42],
);
assertEquals(
attempt(() => {
throw "err";
Expand All @@ -50,6 +53,26 @@ assertEquals(
);
```

## asyncAttempt

`asyncAttempt` is a function that executes a async function and returns the
result (`Promise<[error: unknown, value: T]>`). If the function is successful,
it returns `Promise.resolve([undefined, value])`. If the function throws an
error, it returns `Promise.resolve([error, undefined])`.

```ts
import { assertEquals } from "@std/assert";
import { asyncAttempt } from "@core/errorutil/async-attempt";

assertEquals(await asyncAttempt(async () => 42), [undefined, 42]);
assertEquals(
await asyncAttempt(async () => {
throw "err";
}),
["err", undefined],
);
```

## ErrorObject

`ErrorObject` is a class that wraps an error object for serialization. It is
Expand Down
27 changes: 27 additions & 0 deletions async_attempt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { Result } from "./attempt.ts";

export type AsyncResult<T, E> = Promise<Result<T, E>>;

/**
* Attempt to execute a async function and return a AsyncResult<T, E>.
*
* @param fn - The function to execute.
* @returns A AsyncResult<T, E> where T is the return type of the async function and E is the error type.
*
* @example
* ```ts
* import { asyncAttempt } from "@core/errorutil/async-attempt";
*
* console.log(await asyncAttempt(async () => 1)); // [undefined, 1]
* console.log(await asyncAttempt(async () => { throw "err" })); // ["err", undefined]
* ```
*/
export async function asyncAttempt<T, E = unknown>(
fn: () => Promise<T>,
): Promise<Result<T, E>> {
try {
return [undefined, await fn()];
} catch (e) {
return [e as E, undefined];
}
}
13 changes: 13 additions & 0 deletions async_attempt_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { test } from "@cross/test";
import { assertEquals } from "@std/assert";
import { asyncAttempt } from "./async_attempt.ts";

test("asyncAttempt should return a Success<T> when the async function is successful", async () => {
const result = await asyncAttempt(() => Promise.resolve(1));
assertEquals(result, [undefined, 1]);
});

test("asyncAttempt should return a Failure<E> when the async function is failed", async () => {
const result = await asyncAttempt(() => Promise.reject("err"));
assertEquals(result, ["err", undefined]);
});
18 changes: 5 additions & 13 deletions deno.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
".": "./mod.ts",
"./alter": "./alter.ts",
"./alter-else": "./alter_else.ts",
"./async-attempt": "./async_attempt.ts",
"./attempt": "./attempt.ts",
"./error-object": "./error_object.ts",
"./raise": "./raise.ts",
Expand All @@ -13,25 +14,16 @@
"./unimplemented": "./unimplemented.ts",
"./unreachable": "./unreachable.ts"
},
"exclude": [
".coverage/**"
],
"exclude": [".coverage/**"],
"publish": {
"include": [
"**/*.ts",
"README.md",
"LICENSE"
],
"exclude": [
"**/*_bench.ts",
"**/*_test.ts",
".*"
]
"include": ["**/*.ts", "README.md", "LICENSE"],
"exclude": ["**/*_bench.ts", "**/*_test.ts", ".*"]
},
"imports": {
"@core/errorutil": "./mod.ts",
"@core/errorutil/alter": "./alter.ts",
"@core/errorutil/alter-else": "./alter_else.ts",
"@core/errorutil/async-attempt": "./async_attempt.ts",
"@core/errorutil/attempt": "./attempt.ts",
"@core/errorutil/error-object": "./error_object.ts",
"@core/errorutil/raise": "./raise.ts",
Expand Down
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from "./alter.ts";
export * from "./alter_else.ts";
export * from "./async_attempt.ts";
export * from "./attempt.ts";
export * from "./error_object.ts";
export * from "./raise.ts";
Expand Down