-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
32 lines (29 loc) · 917 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
29
30
31
32
const identity = v => v;
const last = array => array[array.length - 1];
module.export = function abet(promise, steps=[], proxyTarget=()=>{}) {
async function processResult(result) {
for(let step of steps) {
result = await step(result);
}
return result;
}
return new Proxy(proxyTarget, {
get(target, key) {
if(key === 'then') {
return (fn1, fn2) => promise.then(processResult).then(fn1, fn2);
} else if(key === 'catch') {
return fn => promise.then(processResult).catch(fn);
}
return abet(promise, [
...steps,
result => result[key]
], proxyTarget);
},
apply(target, thisArg, args) {
const getMethod = last(steps) || identity;
const newSteps = steps.slice(0, -1);
newSteps.push(result => getMethod(result).apply(result, args));
return abet(promise, newSteps, proxyTarget);
}
});
}