-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
37 lines (34 loc) · 937 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
33
34
35
36
37
/**
* Wrap an "unsafe" promise
*/
var safePromise = module.exports.safePromise = function safePromise(promise) {
return promise
.then(function(result) {
return [undefined, result];
})
.catch(function(error) {
return [error, undefined];
});
}
/**
* Wrap an "unsafe" function that might throw
* upon execution in a function that returns
* a promise (which is handled "safely" with safePromise)
*
* NOTE: This will only handle throws that
* are done within the same execution tick,
* and not errors that are thrown "later"
* within the same context (no way to do that..)
*/
var safeFunction = module.exports.safeFunction = function safeFunction(fn) {
return function() {
var error = undefined;
var result = undefined;
try {
result = fn.apply(this, arguments);
} catch (e) {
error = e;
}
return safePromise(error ? Promise.reject(error) : Promise.resolve(result));
}
}