-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #41 from jsr-core/add-promish
feat(ensurePromise): add `ensurePromise` function
- Loading branch information
Showing
4 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<T>(value: T): Promise<T> { | ||
return value instanceof Promise ? value : Promise.resolve(value); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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); | ||
}); |