-
Notifications
You must be signed in to change notification settings - Fork 1
/
no-async-hook.ts
93 lines (79 loc) · 2.34 KB
/
no-async-hook.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
type Destructor = () => void;
/**
* Converts an async style function into an effect which can be supplied to useEffect.
* useEffectAsync(() => Async(async signal => { ... }), [...]);
* @param promise any promise, don't forget to utilize the AbortSignal when calling other async functions.
* @returns A function that aborts the AbortSignal.
*/
export const Async = (promise: (signal: AbortSignal) => Promise<void>): Destructor => {
const abortReason = Symbol('promise aborted / do not catch');
const controller = new AbortController();
const signal = controller.signal;
promise(signal).catch(error => {
if (!signal.aborted && error !== abortReason) {
throw error;
}
});
return () => controller.abort(abortReason);
}
/**
* Converts an effect style function into a promise.
* @param effect implement an effect and use the two arguments to effect resolve and reject to complete it.
* @param signal a signal with which you can abort the returned promise.
* @returns a promise.
*/
export const Effect = <T>(
effect: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => (Destructor | void),
signal: AbortSignal
): Promise<T> => {
if (signal.aborted) return Promise.reject(signal.reason);
return new Promise<T>((resolve, reject) => {
try {
let hasDestructorBeenCalled = false;
const freeResources = () => {
if (hasDestructorBeenCalled) return;
else hasDestructorBeenCalled = true;
signal.removeEventListener('abort', onAbort);
try {
destructor?.();
}
catch (error) {
console.error(
"An error occurred inside an Effect Destructor call. " +
"Consider adding an error boundary to your Effect Destructor function.",
error
);
}
}
const onAbort = () => {
freeResources();
reject(signal.reason);
}
const destructor = effect(
value => {
freeResources();
resolve(value);
},
reason => {
freeResources();
reject(reason);
}
);
signal.addEventListener('abort', onAbort);
}
catch (e) {
reject(e);
}
});
};
/*
export const Signal = (effect: (abort: (reason?: any) => void) => (Destructor | void)): AbortSignal => {
const controller = new AbortController();
const signal = controller.signal;
const destructor = effect(reason => {
destructor?.();
controller.abort(reason);
})
return signal;
}
*/