-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathpromisify
More file actions
29 lines (26 loc) · 761 Bytes
/
promisify
File metadata and controls
29 lines (26 loc) · 761 Bytes
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
function promisify(subject) {
return (...args) => new Promise(async (resolve, reject) => {
const callbackHandler = (...results) => {
// filter error from results to remove dependency on error, result order
const {error, result} = results.reduce((obj, res) => {
if(res instanceof Error) {
obj['error'] = res;
} else {
obj['result'] = res;
}
return obj;
}, {});
if(error) {
reject(error);
} else {
resolve(result);
}
}
try {
const result = await subject(...args, callbackHandler);
resolve(result); // only runs if callbackHandler does not resolve the promise
} catch(error) {
reject(error);
}
});
}