-
Notifications
You must be signed in to change notification settings - Fork 532
/
Copy pathpromises.js
45 lines (38 loc) · 1.1 KB
/
promises.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
let Promise = global.Promise;
/// encapsulate a method with a node-style callback in a Promise
/// @param {object} 'this' of the encapsulated function
/// @param {function} function to be encapsulated
/// @param {Array-like} args to be passed to the called function
/// @return {Promise} a Promise encapsulating the function
function promise(fn, context, args) {
if (!Array.isArray(args)) {
args = Array.prototype.slice.call(args);
}
if (typeof fn !== 'function') {
return Promise.reject(new Error('fn must be a function'));
}
return new Promise((resolve, reject) => {
args.push((err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
fn.apply(context, args);
});
}
/// @param {err} the error to be thrown
function reject(err) {
return Promise.reject(err);
}
/// changes the promise implementation that bcrypt uses
/// @param {Promise} the implementation to use
function use(promise) {
Promise = promise;
}
module.exports = {
promise,
reject,
use
}