We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 2a29d44 commit 71c98e4Copy full SHA for 71c98e4
1 file changed
L-A/0010 Design Cancellable Function (L-A)/Design Cancellable Function.js
@@ -0,0 +1,22 @@
1
+const cancellable = (generator) => {
2
+ let cancel;
3
+ const cancelPromise = new Promise((_, reject) => {
4
+ cancel = () => reject("Cancelled");
5
+ });
6
+ // Every Promise rejection has to be caught.
7
+ cancelPromise.catch(() => {});
8
+
9
+ const promise = (async () => {
10
+ let next = generator.next();
11
+ while (!next.done) {
12
+ try {
13
+ next = generator.next(await Promise.race([next.value, cancelPromise]));
14
+ } catch (e) {
15
+ next = generator.throw(e);
16
+ }
17
18
+ return next.value;
19
+ })();
20
21
+ return [cancel, promise];
22
+};
0 commit comments