promises.js
1 let Promise = global.Promise; 2 3 /// encapsulate a method with a node-style callback in a Promise 4 /// @param {object} 'this' of the encapsulated function 5 /// @param {function} function to be encapsulated 6 /// @param {Array-like} args to be passed to the called function 7 /// @return {Promise} a Promise encapsulating the function 8 function promise(fn, context, args) { 9 if (!Array.isArray(args)) { 10 args = Array.prototype.slice.call(args); 11 } 12 13 if (typeof fn !== 'function') { 14 return Promise.reject(new Error('fn must be a function')); 15 } 16 17 return new Promise((resolve, reject) => { 18 args.push((err, data) => { 19 if (err) { 20 reject(err); 21 } else { 22 resolve(data); 23 } 24 }); 25 26 fn.apply(context, args); 27 }); 28 } 29 30 /// @param {err} the error to be thrown 31 function reject(err) { 32 return Promise.reject(err); 33 } 34 35 /// changes the promise implementation that bcrypt uses 36 /// @param {Promise} the implementation to use 37 function use(promise) { 38 Promise = promise; 39 } 40 41 module.exports = { 42 promise, 43 reject, 44 use 45 }