-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmake-cancelable.ts
66 lines (61 loc) · 1.58 KB
/
make-cancelable.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
/**
* Please refer to the terms of the license agreement in the root of the project
*
* (c) 2024 Feedzai
*/
/**
* Helper method that wraps a normal Promise and allows it to be cancelled.
*/
export interface MakeCancelablePromise<GenericReturnValue = unknown> {
/**
* Holds the promise itself
*/
promise: Promise<GenericReturnValue>;
/**
* Rejects the promise by cancelling it
*/
cancel: () => void;
}
/**
* Helper method that wraps a normal Promise and allows it to be cancelled.
*
* @example
*
* ```js
* import { wait } from "@joaomtmdias/js-utilities";
*
* // A Promise that resolves after 1 second
* const somePromise = wait(1000);
*
* // Can also be made cancellable by wrapping it
* const cancelable = makeCancelable(somePromise);
*
* // So that when we execute said wrapped promise...
* cancelable.promise
* .then(console.log)
* .catch(({ isCanceled }) => console.error('isCanceled', isCanceled));
*
* // We can cancel it on demand
* cancelable.cancel();
* ```
*/
export function makeCancelable<GenericPromiseValue = unknown>(
promise: Promise<GenericPromiseValue>
): MakeCancelablePromise<GenericPromiseValue> {
let hasCanceled_ = false;
const wrappedPromise = new Promise<GenericPromiseValue>((resolve, reject) => {
promise
.then((val) => {
return hasCanceled_ ? reject({ isCanceled: true }) : resolve(val);
})
.catch((error) => {
return hasCanceled_ ? reject({ isCanceled: true }) : reject(error);
});
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
}