tagu-tagu 4.2.1 → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/flow/Await.ts +59 -0
package/package.json
CHANGED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { useState } from "../signal/Signal";
|
|
2
|
+
import type { ControlFlow } from "./ControlFlow";
|
|
3
|
+
import { Switch } from "./Switch";
|
|
4
|
+
|
|
5
|
+
export function Await(
|
|
6
|
+
promise: Promise<Element>,
|
|
7
|
+
options?: {
|
|
8
|
+
pending?: () => Element;
|
|
9
|
+
rejected?: (error: any) => Element;
|
|
10
|
+
},
|
|
11
|
+
): ControlFlow;
|
|
12
|
+
export function Await<T>(
|
|
13
|
+
promise: Promise<T>,
|
|
14
|
+
options?: {
|
|
15
|
+
pending?: () => Element;
|
|
16
|
+
fulfilled: (value: T) => Element;
|
|
17
|
+
rejected?: (error: any) => Element;
|
|
18
|
+
},
|
|
19
|
+
): ControlFlow;
|
|
20
|
+
export function Await<T>(
|
|
21
|
+
promise: Promise<T>,
|
|
22
|
+
options?: {
|
|
23
|
+
pending?: () => Element;
|
|
24
|
+
fulfilled?: (value: T) => Element;
|
|
25
|
+
rejected?: (error: any) => Element;
|
|
26
|
+
},
|
|
27
|
+
) {
|
|
28
|
+
const pending = "pending";
|
|
29
|
+
const fulfilled = "fulfilled";
|
|
30
|
+
const rejected = "rejected";
|
|
31
|
+
const promiseState = useState(pending);
|
|
32
|
+
|
|
33
|
+
let value: T;
|
|
34
|
+
let error: any;
|
|
35
|
+
promise
|
|
36
|
+
.then((v) => {
|
|
37
|
+
value = v;
|
|
38
|
+
promiseState.set(fulfilled);
|
|
39
|
+
})
|
|
40
|
+
.catch((reason) => {
|
|
41
|
+
error = reason;
|
|
42
|
+
promiseState.set(rejected);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const switchOptions = {} as Record<string, () => Element>;
|
|
46
|
+
|
|
47
|
+
if (options?.pending) {
|
|
48
|
+
switchOptions[pending] = options.pending;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
switchOptions[fulfilled] = () =>
|
|
52
|
+
options?.fulfilled?.(value) ?? (value as Element);
|
|
53
|
+
|
|
54
|
+
if (options?.rejected) {
|
|
55
|
+
switchOptions[rejected] = () => options.rejected!(error);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return Switch(promiseState, switchOptions);
|
|
59
|
+
}
|