-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathc-expirable.js
69 lines (62 loc) · 1.5 KB
/
c-expirable.js
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
'use strict';
const PROMISE_TIMEOUT = 1000;
class Expirable {
constructor(executor) {
const promise = new Promise((resolve, reject) => {
executor((val) => {
if (this.expired) return;
clearTimeout(this.timer);
resolve(val);
}, (err) => {
if (this.expired) return;
clearTimeout(this.timer);
reject(err);
});
this.timer = setTimeout(() => {
this.expired = true;
reject(new Error('Expired'));
}, PROMISE_TIMEOUT);
});
this.promise = promise;
this.expired = false;
this.timer = null;
return this.promise;
}
}
// Usage
new Expirable((resolve) => {
setTimeout(() => {
resolve('Resolved before timeout');
}, 100);
}).then((data) => {
console.dir({ data });
}).catch((error) => {
console.dir({ error: error.message });
});
new Expirable((resolve, reject) => {
setTimeout(() => {
reject(new Error('Something went wrong'));
}, 100);
}).then((data) => {
console.dir({ data });
}).catch((error) => {
console.dir({ error: error.message });
});
new Expirable((resolve) => {
setTimeout(() => {
resolve('Never resolved before timeout');
}, 2000);
}).then((data) => {
console.dir({ data });
}).catch((error) => {
console.dir({ error: error.message });
});
new Expirable((resolve, reject) => {
setTimeout(() => {
reject(new Error('Never rejected before timeout'));
}, 2000);
}).then((data) => {
console.dir({ data });
}).catch((error) => {
console.dir({ error: error.message });
});