File tree Expand file tree Collapse file tree 3 files changed +34
-0
lines changed Expand file tree Collapse file tree 3 files changed +34
-0
lines changed Original file line number Diff line number Diff line change 5
5
"." : " ./mod.ts" ,
6
6
"./async-value" : " ./async_value.ts" ,
7
7
"./barrier" : " ./barrier.ts" ,
8
+ "./ensure-promise" : " ./ensure_promise.ts" ,
8
9
"./lock" : " ./lock.ts" ,
9
10
"./mutex" : " ./mutex.ts" ,
10
11
"./notify" : " ./notify.ts" ,
34
35
"@core/asyncutil" : " ./mod.ts" ,
35
36
"@core/asyncutil/async-value" : " ./async_value.ts" ,
36
37
"@core/asyncutil/barrier" : " ./barrier.ts" ,
38
+ "@core/asyncutil/ensure-promise" : " ./ensure_promise.ts" ,
37
39
"@core/asyncutil/lock" : " ./lock.ts" ,
38
40
"@core/asyncutil/mutex" : " ./mutex.ts" ,
39
41
"@core/asyncutil/notify" : " ./notify.ts" ,
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Ensure that a value is a promise.
3
+ *
4
+ * It returns the value if it is already a promise, otherwise it returns a
5
+ * promise that resolves to the value.
6
+ *
7
+ * @param value - The value to ensure as a promise.
8
+ * @returns A promise that resolves to the value.
9
+ *
10
+ * ```ts
11
+ * import { assertEquals } from "@std/assert";
12
+ * import { ensurePromise } from "@core/asyncutil/ensure-promise";
13
+ *
14
+ * assertEquals(await ensurePromise(42), 42);
15
+ * assertEquals(await ensurePromise(Promise.resolve(42)), 42);
16
+ * ```
17
+ */
18
+ export function ensurePromise < T > ( value : T ) : Promise < T > {
19
+ return value instanceof Promise ? value : Promise . resolve ( value ) ;
20
+ }
Original file line number Diff line number Diff line change
1
+ import { test } from "@cross/test" ;
2
+ import { assertEquals } from "@std/assert" ;
3
+ import { ensurePromise } from "./ensure_promise.ts" ;
4
+
5
+ test ( "ensurePromise() returns the value if it is already a promise" , async ( ) => {
6
+ const p = Promise . resolve ( 42 ) ;
7
+ assertEquals ( await ensurePromise ( p ) , 42 ) ;
8
+ } ) ;
9
+
10
+ test ( "ensurePromise() returns a promise that resolves to the value" , async ( ) => {
11
+ assertEquals ( await ensurePromise ( 42 ) , 42 ) ;
12
+ } ) ;
You can’t perform that action at this time.
0 commit comments