promises.js 1.1 KB

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