race.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = race;
  6. var _isArray = require('lodash/isArray');
  7. var _isArray2 = _interopRequireDefault(_isArray);
  8. var _noop = require('lodash/noop');
  9. var _noop2 = _interopRequireDefault(_noop);
  10. var _once = require('./internal/once');
  11. var _once2 = _interopRequireDefault(_once);
  12. var _wrapAsync = require('./internal/wrapAsync');
  13. var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
  14. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  15. /**
  16. * Runs the `tasks` array of functions in parallel, without waiting until the
  17. * previous function has completed. Once any of the `tasks` complete or pass an
  18. * error to its callback, the main `callback` is immediately called. It's
  19. * equivalent to `Promise.race()`.
  20. *
  21. * @name race
  22. * @static
  23. * @memberOf module:ControlFlow
  24. * @method
  25. * @category Control Flow
  26. * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
  27. * to run. Each function can complete with an optional `result` value.
  28. * @param {Function} callback - A callback to run once any of the functions have
  29. * completed. This function gets an error or result from the first function that
  30. * completed. Invoked with (err, result).
  31. * @returns undefined
  32. * @example
  33. *
  34. * async.race([
  35. * function(callback) {
  36. * setTimeout(function() {
  37. * callback(null, 'one');
  38. * }, 200);
  39. * },
  40. * function(callback) {
  41. * setTimeout(function() {
  42. * callback(null, 'two');
  43. * }, 100);
  44. * }
  45. * ],
  46. * // main callback
  47. * function(err, result) {
  48. * // the result will be equal to 'two' as it finishes earlier
  49. * });
  50. */
  51. function race(tasks, callback) {
  52. callback = (0, _once2.default)(callback || _noop2.default);
  53. if (!(0, _isArray2.default)(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
  54. if (!tasks.length) return callback();
  55. for (var i = 0, l = tasks.length; i < l; i++) {
  56. (0, _wrapAsync2.default)(tasks[i])(callback);
  57. }
  58. }
  59. module.exports = exports['default'];