-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
58 lines (49 loc) · 1.76 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
51
52
53
54
55
56
57
58
const resolver = (item, timeout, ...params) => {
if (typeof timeout != "number" || timeout < 0) {
timeout = null;
}
if (item instanceof Promise && timeout == null) {
return item.then(result => [null, result]).catch(err => [err, null]);
}
let promisedItem = new Promise((resolve, reject) => {
if (timeout == null) {
if (item instanceof Function) {
item = item.apply(null, params);
}
if (item instanceof Error) {
reject(item);
}
resolve(item);
} else {
/**
* A promise will reject in the current event loop
* whereas setTimeout schedules the callback to execute (at the end of the next tick)
* after a minimum threshold in ms has elapsed
* So a catch should be added in this event loop to prevent UnhandledPromiseRejection
*/
if (item instanceof Promise) {
item.catch(reason => {
setTimeout(() => {
reject(reason);
}, timeout);
});
}
setTimeout(() => {
if (item instanceof Function) {
item = item.apply(null, params);
}
if (item instanceof Error) {
reject(item);
}
if (item instanceof Promise) {
item.then(resolve).catch(reject);
} else {
resolve(item);
}
}, timeout);
}
});
return promisedItem.then(result => [null, result]).catch(err => [err, null]);
};
resolver.sleep = ms => resolver(null, ms);
module.exports = resolver;