reflect.js 2.2 KB

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