reflectAll.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = reflectAll;
  6. var _reflect = require('./reflect.js');
  7. var _reflect2 = _interopRequireDefault(_reflect);
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. /**
  10. * A helper function that wraps an array or an object of functions with `reflect`.
  11. *
  12. * @name reflectAll
  13. * @static
  14. * @memberOf module:Utils
  15. * @method
  16. * @see [async.reflect]{@link module:Utils.reflect}
  17. * @category Util
  18. * @param {Array|Object|Iterable} tasks - The collection of
  19. * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.
  20. * @returns {Array} Returns an array of async functions, each wrapped in
  21. * `async.reflect`
  22. * @example
  23. *
  24. * let tasks = [
  25. * function(callback) {
  26. * setTimeout(function() {
  27. * callback(null, 'one');
  28. * }, 200);
  29. * },
  30. * function(callback) {
  31. * // do some more stuff but error ...
  32. * callback(new Error('bad stuff happened'));
  33. * },
  34. * function(callback) {
  35. * setTimeout(function() {
  36. * callback(null, 'two');
  37. * }, 100);
  38. * }
  39. * ];
  40. *
  41. * async.parallel(async.reflectAll(tasks),
  42. * // optional callback
  43. * function(err, results) {
  44. * // values
  45. * // results[0].value = 'one'
  46. * // results[1].error = Error('bad stuff happened')
  47. * // results[2].value = 'two'
  48. * });
  49. *
  50. * // an example using an object instead of an array
  51. * let tasks = {
  52. * one: function(callback) {
  53. * setTimeout(function() {
  54. * callback(null, 'one');
  55. * }, 200);
  56. * },
  57. * two: function(callback) {
  58. * callback('two');
  59. * },
  60. * three: function(callback) {
  61. * setTimeout(function() {
  62. * callback(null, 'three');
  63. * }, 100);
  64. * }
  65. * };
  66. *
  67. * async.parallel(async.reflectAll(tasks),
  68. * // optional callback
  69. * function(err, results) {
  70. * // values
  71. * // results.one.value = 'one'
  72. * // results.two.error = 'two'
  73. * // results.three.value = 'three'
  74. * });
  75. */
  76. function reflectAll(tasks) {
  77. var results;
  78. if (Array.isArray(tasks)) {
  79. results = tasks.map(_reflect2.default);
  80. } else {
  81. results = {};
  82. Object.keys(tasks).forEach(key => {
  83. results[key] = _reflect2.default.call(this, tasks[key]);
  84. });
  85. }
  86. return results;
  87. }
  88. module.exports = exports['default'];