reflect.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = reflect;
  6. var _initialParams = require('./internal/initialParams');
  7. var _initialParams2 = _interopRequireDefault(_initialParams);
  8. var _slice = require('./internal/slice');
  9. var _slice2 = _interopRequireDefault(_slice);
  10. var _wrapAsync = require('./internal/wrapAsync');
  11. var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. /**
  14. * Wraps the async function in another function that always completes with a
  15. * result object, even when it errors.
  16. *
  17. * The result object has either the property `error` or `value`.
  18. *
  19. * @name reflect
  20. * @static
  21. * @memberOf module:Utils
  22. * @method
  23. * @category Util
  24. * @param {AsyncFunction} fn - The async function you want to wrap
  25. * @returns {Function} - A function that always passes null to it's callback as
  26. * the error. The second argument to the callback will be an `object` with
  27. * either an `error` or a `value` property.
  28. * @example
  29. *
  30. * async.parallel([
  31. * async.reflect(function(callback) {
  32. * // do some stuff ...
  33. * callback(null, 'one');
  34. * }),
  35. * async.reflect(function(callback) {
  36. * // do some more stuff but error ...
  37. * callback('bad stuff happened');
  38. * }),
  39. * async.reflect(function(callback) {
  40. * // do some more stuff ...
  41. * callback(null, 'two');
  42. * })
  43. * ],
  44. * // optional callback
  45. * function(err, results) {
  46. * // values
  47. * // results[0].value = 'one'
  48. * // results[1].error = 'bad stuff happened'
  49. * // results[2].value = 'two'
  50. * });
  51. */
  52. function reflect(fn) {
  53. var _fn = (0, _wrapAsync2.default)(fn);
  54. return (0, _initialParams2.default)(function reflectOn(args, reflectCallback) {
  55. args.push(function callback(error, cbArg) {
  56. if (error) {
  57. reflectCallback(null, { error: error });
  58. } else {
  59. var value;
  60. if (arguments.length <= 2) {
  61. value = cbArg;
  62. } else {
  63. value = (0, _slice2.default)(arguments, 1);
  64. }
  65. reflectCallback(null, { value: value });
  66. }
  67. });
  68. return _fn.apply(this, args);
  69. });
  70. }
  71. module.exports = exports['default'];