diff --git a/README.md b/README.md index 29542a5..22c6e19 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,20 @@ worker(2); worker(3); ``` +### ensurePromise + +`ensurePromise` is a utility function that ensures a value is a promise. + +```ts +import { ensurePromise } from "@core/asyncutil/ensure-promise"; + +const p1 = ensurePromise(Promise.resolve("Resolved promise")); +console.log(await p1); // Resolved promise + +const p2 = ensurePromise("Not a promise"); +console.log(await p2); // Not a promise +``` + ### Lock/RwLock `Lock` is a mutual exclusion lock that provides safe concurrent access to a diff --git a/deno.jsonc b/deno.jsonc index 67aa3d3..2d12f52 100644 --- a/deno.jsonc +++ b/deno.jsonc @@ -5,6 +5,7 @@ ".": "./mod.ts", "./async-value": "./async_value.ts", "./barrier": "./barrier.ts", + "./ensure-promise": "./ensure_promise.ts", "./lock": "./lock.ts", "./mutex": "./mutex.ts", "./notify": "./notify.ts", @@ -34,6 +35,7 @@ "@core/asyncutil": "./mod.ts", "@core/asyncutil/async-value": "./async_value.ts", "@core/asyncutil/barrier": "./barrier.ts", + "@core/asyncutil/ensure-promise": "./ensure_promise.ts", "@core/asyncutil/lock": "./lock.ts", "@core/asyncutil/mutex": "./mutex.ts", "@core/asyncutil/notify": "./notify.ts", diff --git a/ensure_promise.ts b/ensure_promise.ts new file mode 100644 index 0000000..5dde7da --- /dev/null +++ b/ensure_promise.ts @@ -0,0 +1,20 @@ +/** + * Ensure that a value is a promise. + * + * It returns the value if it is already a promise, otherwise it returns a + * promise that resolves to the value. + * + * @param value - The value to ensure as a promise. + * @returns A promise that resolves to the value. + * + * ```ts + * import { assertEquals } from "@std/assert"; + * import { ensurePromise } from "@core/asyncutil/ensure-promise"; + * + * assertEquals(await ensurePromise(42), 42); + * assertEquals(await ensurePromise(Promise.resolve(42)), 42); + * ``` + */ +export function ensurePromise(value: T): Promise { + return value instanceof Promise ? value : Promise.resolve(value); +} diff --git a/ensure_promise_test.ts b/ensure_promise_test.ts new file mode 100644 index 0000000..3c63b9a --- /dev/null +++ b/ensure_promise_test.ts @@ -0,0 +1,12 @@ +import { test } from "@cross/test"; +import { assertEquals } from "@std/assert"; +import { ensurePromise } from "./ensure_promise.ts"; + +test("ensurePromise() returns the value if it is already a promise", async () => { + const p = Promise.resolve(42); + assertEquals(await ensurePromise(p), 42); +}); + +test("ensurePromise() returns a promise that resolves to the value", async () => { + assertEquals(await ensurePromise(42), 42); +});