-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peek_promise_state.ts
41 lines (39 loc) · 1.37 KB
/
peek_promise_state.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const t = Symbol("pending mark");
/**
* Promise state
*/
export type PromiseState = "fulfilled" | "rejected" | "pending";
/**
* Peek the current state (fulfilled, rejected, or pending) of the promise.
*
* ```ts
* import { assertEquals } from "@std/assert";
* import { peekPromiseState } from "@core/asyncutil/peek-promise-state";
*
* assertEquals(await peekPromiseState(Promise.resolve("value")), "fulfilled");
* assertEquals(await peekPromiseState(Promise.reject("error")), "rejected");
* assertEquals(await peekPromiseState(new Promise(() => {})), "pending");
* ```
*
* Use {@linkcode https://jsr.io/@core/asyncutil/doc/flush-promises/~/flushPromises flushPromises}
* to wait for all pending promises to be resolved prior to calling this function.
*
* ```ts
* import { assertEquals } from "@std/assert";
* import { flushPromises } from "@core/asyncutil/flush-promises";
* import { peekPromiseState } from "@core/asyncutil/peek-promise-state";
*
* const p = Promise.resolve<void>(undefined)
* .then(() => {})
* .then(() => {});
* assertEquals(await peekPromiseState(p), "pending");
* await flushPromises();
* assertEquals(await peekPromiseState(p), "fulfilled");
* ```
*/
export function peekPromiseState(p: Promise<unknown>): Promise<PromiseState> {
return Promise.race([p, t]).then(
(v) => (v === t ? "pending" : "fulfilled"),
() => "rejected",
);
}