Açıklama Yok

index.js 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. var processFn = function (fn, P, opts) {
  3. return function () {
  4. var that = this;
  5. var args = new Array(arguments.length);
  6. for (var i = 0; i < arguments.length; i++) {
  7. args[i] = arguments[i];
  8. }
  9. return new P(function (resolve, reject) {
  10. args.push(function (err, result) {
  11. if (err) {
  12. reject(err);
  13. } else if (opts.multiArgs) {
  14. var results = new Array(arguments.length - 1);
  15. for (var i = 1; i < arguments.length; i++) {
  16. results[i - 1] = arguments[i];
  17. }
  18. resolve(results);
  19. } else {
  20. resolve(result);
  21. }
  22. });
  23. fn.apply(that, args);
  24. });
  25. };
  26. };
  27. var pify = module.exports = function (obj, P, opts) {
  28. if (typeof P !== 'function') {
  29. opts = P;
  30. P = Promise;
  31. }
  32. opts = opts || {};
  33. opts.exclude = opts.exclude || [/.+Sync$/];
  34. var filter = function (key) {
  35. var match = function (pattern) {
  36. return typeof pattern === 'string' ? key === pattern : pattern.test(key);
  37. };
  38. return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
  39. };
  40. var ret = typeof obj === 'function' ? function () {
  41. if (opts.excludeMain) {
  42. return obj.apply(this, arguments);
  43. }
  44. return processFn(obj, P, opts).apply(this, arguments);
  45. } : {};
  46. return Object.keys(obj).reduce(function (ret, key) {
  47. var x = obj[key];
  48. ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x;
  49. return ret;
  50. }, ret);
  51. };
  52. pify.all = pify;