race.js 2.1 KB

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