From b31cefa824ff9bc480502df061ba949feb25d2ee Mon Sep 17 00:00:00 2001 From: bkiac Date: Mon, 19 Aug 2024 11:40:00 +0200 Subject: [PATCH] Add generator docs --- readme.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ src/try.ts | 4 ++-- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/readme.md b/readme.md index 95ec757..e6f14c1 100644 --- a/readme.md +++ b/readme.md @@ -39,6 +39,7 @@ - [Option](#option) - [AsyncOption](#asyncoption) - [Utilities](#utilities) + - [Generators](#generators) - [Testing](#testing) - [Similar Libraries](#similar-libraries) @@ -495,6 +496,50 @@ Returns `true` if `value` is an instance of `Option`. Returns `true` if `value` is an instance of `AsyncOption`. +### Generators + +These utilities help your code appear and behave more like traditional synchronous code by propagating errors automatically. + +Note that TS sometimes has trouble inferring yielded result type, especially when a lot of `yield*` operations are used in a single function. For complex cases, you may need to explicitly type the result or revert to handling `Results` directly. + +#### `trySync(f: Function): Result` + +Runs a generator function that returns a `Result` and infers its return type as `Result`. + +`yield*` must be used to yield the result of a `Result`. + +```ts +// Result +const result = tryFn(function* () { + const a = yield* Ok(1); + const random = Math.random(); + if (random > 0.5) { + yield* Err("error"); + } + return a + random; +}); +``` + +#### `tryAsync(f: Function): AsyncResult` + +Runs an async generator function that returns a `Result` and infers its return type as `AsyncResult`. + +`yield*` must be used to yield the result of a `AsyncResult` or `Result`. + +```ts +const okOne = () => new AsyncResult(Promise.resolve(Ok(1))); + +// AsyncResult +const result = tryAsync(async function* () { + const a = yield* okOne(); + const random = Math.random(); + if (random > 0.5) { + yield* Err("error"); + } + return a + random; +}); +``` + ## Testing Adding an iterator to the Result class has introduced behavior that affects how testing libraries handle deep comparisons of instances of this class. diff --git a/src/try.ts b/src/try.ts index b112ef9..2f18da6 100644 --- a/src/try.ts +++ b/src/try.ts @@ -11,7 +11,7 @@ import type {InferErr} from "./util"; * * ```ts * // $ExpectType Result - * const result = tryFn(function* () { + * const result = trySync(function* () { * const a = yield* Ok(1) * const random = Math.random() * if (random > 0.5) { @@ -62,7 +62,7 @@ async function toPromiseResult(value: any): Promise> { * const okOne = () => new AsyncResult(Promise.resolve(Ok(1))) * * // $ExpectType AsyncResult - * const result = tryAsyncFn(async function* () { + * const result = tryAsync(async function* () { * const a = yield* okOne() * const random = Math.random() * if (random > 0.5) {