promises.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. var Promise = global.Promise;
  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. module.exports.promise = function (fn, context, args) {
  9. if (!Array.isArray(args)) {
  10. args = Array.prototype.slice.call(args);
  11. }
  12. if (typeof fn !== 'function') {
  13. return Promise.reject(new Error('fn must be a function'));
  14. }
  15. return new Promise(function(resolve, reject) {
  16. args.push(function(err, data) {
  17. if (err) {
  18. reject(err);
  19. } else {
  20. resolve(data);
  21. }
  22. });
  23. fn.apply(context, args);
  24. });
  25. };
  26. /// @param {err} the error to be thrown
  27. module.exports.reject = function (err) {
  28. return Promise.reject(err);
  29. };
  30. /// changes the promise implementation that bcrypt uses
  31. /// @param {Promise} the implementation to use
  32. module.exports.use = function(promise) {
  33. Promise = promise;
  34. };