-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
28 lines (22 loc) · 995 Bytes
/
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
//Trick to transform Promises into functors
Promise.prototype.map = Promise.prototype.then;
const expire = (ms,name='Promise') => new Promise((resolve, reject) => {
let id = setTimeout(() => {
clearTimeout(id);
reject(`${name} timed out in ${ms} ms.`)
}, ms)
});
const isAPromise = promise => promise instanceof Promise;
const reflect = promise => promise.then(val => ({val, status: "resolved" }), err => ({err, status: "rejected" }));
const timeout = (promise, ms, name = 'Promise') => {
if(!isAPromise(promise))
{
throw 'Timeout can only receive a single promise!';
}
return Promise.race([promise,expire(ms,name)]);
}
const firstIfArray = arr => Array.isArray(arr[0]) ? arr[0] : arr;
const first = (...promises) => Promise.race(firstIfArray(promises));
const all = (...promises) => Promise.all(firstIfArray(promises));
const any = (...promises) => Promise.all(firstIfArray(promises).map(reflect));
module.exports = {all, first, timeout, any};