-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
50 lines (42 loc) · 1.29 KB
/
index.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
var noop = function noop () {};
// HOF Wraps the native Promise API
// to add take a shouldCancel promise and add
// an onCancel() callback.
var speculation = function speculation (fn) {
// Don't cancel by default
var cancel = (
arguments.length > 1 &&
arguments[1] !== undefined
) ? arguments[1] : Promise.reject();
return new Promise(function (_resolve, _reject) {
// Track if the promise becomes resolved or rejected to
// avoid invoking onCancel after a promise becomes isSettled.
var isSettled = false;
// When the callsite resolves, mark the promise as fulfilled.
var resolve = function resolve (input) {
isSettled = true;
_resolve(input);
};
// When the callsite rejects, mark the promise as fulfilled.
var reject = function reject (input) {
isSettled = true;
_reject(input);
};
var onCancel = function onCancel (handleCancel) {
var maybeHandleCancel = function (value) {
if (!isSettled) handleCancel(value);
};
return cancel.then(
maybeHandleCancel,
// Ignore expected cancel rejections:
noop
)
// handle onCancel errors
.catch(function (e) {
return reject(e);
});
};
fn(resolve, reject, onCancel);
});
};
module.exports = speculation;