You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5609 lines
181 KiB

4 years ago
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.async = global.async || {})));
  5. }(this, (function (exports) { 'use strict';
  6. function slice(arrayLike, start) {
  7. start = start|0;
  8. var newLen = Math.max(arrayLike.length - start, 0);
  9. var newArr = Array(newLen);
  10. for(var idx = 0; idx < newLen; idx++) {
  11. newArr[idx] = arrayLike[start + idx];
  12. }
  13. return newArr;
  14. }
  15. /**
  16. * Creates a continuation function with some arguments already applied.
  17. *
  18. * Useful as a shorthand when combined with other control flow functions. Any
  19. * arguments passed to the returned function are added to the arguments
  20. * originally passed to apply.
  21. *
  22. * @name apply
  23. * @static
  24. * @memberOf module:Utils
  25. * @method
  26. * @category Util
  27. * @param {Function} fn - The function you want to eventually apply all
  28. * arguments to. Invokes with (arguments...).
  29. * @param {...*} arguments... - Any number of arguments to automatically apply
  30. * when the continuation is called.
  31. * @returns {Function} the partially-applied function
  32. * @example
  33. *
  34. * // using apply
  35. * async.parallel([
  36. * async.apply(fs.writeFile, 'testfile1', 'test1'),
  37. * async.apply(fs.writeFile, 'testfile2', 'test2')
  38. * ]);
  39. *
  40. *
  41. * // the same process without using apply
  42. * async.parallel([
  43. * function(callback) {
  44. * fs.writeFile('testfile1', 'test1', callback);
  45. * },
  46. * function(callback) {
  47. * fs.writeFile('testfile2', 'test2', callback);
  48. * }
  49. * ]);
  50. *
  51. * // It's possible to pass any number of additional arguments when calling the
  52. * // continuation:
  53. *
  54. * node> var fn = async.apply(sys.puts, 'one');
  55. * node> fn('two', 'three');
  56. * one
  57. * two
  58. * three
  59. */
  60. var apply = function(fn/*, ...args*/) {
  61. var args = slice(arguments, 1);
  62. return function(/*callArgs*/) {
  63. var callArgs = slice(arguments);
  64. return fn.apply(null, args.concat(callArgs));
  65. };
  66. };
  67. var initialParams = function (fn) {
  68. return function (/*...args, callback*/) {
  69. var args = slice(arguments);
  70. var callback = args.pop();
  71. fn.call(this, args, callback);
  72. };
  73. };
  74. /**
  75. * Checks if `value` is the
  76. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  77. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  78. *
  79. * @static
  80. * @memberOf _
  81. * @since 0.1.0
  82. * @category Lang
  83. * @param {*} value The value to check.
  84. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  85. * @example
  86. *
  87. * _.isObject({});
  88. * // => true
  89. *
  90. * _.isObject([1, 2, 3]);
  91. * // => true
  92. *
  93. * _.isObject(_.noop);
  94. * // => true
  95. *
  96. * _.isObject(null);
  97. * // => false
  98. */
  99. function isObject(value) {
  100. var type = typeof value;
  101. return value != null && (type == 'object' || type == 'function');
  102. }
  103. var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
  104. var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
  105. function fallback(fn) {
  106. setTimeout(fn, 0);
  107. }
  108. function wrap(defer) {
  109. return function (fn/*, ...args*/) {
  110. var args = slice(arguments, 1);
  111. defer(function () {
  112. fn.apply(null, args);
  113. });
  114. };
  115. }
  116. var _defer;
  117. if (hasSetImmediate) {
  118. _defer = setImmediate;
  119. } else if (hasNextTick) {
  120. _defer = process.nextTick;
  121. } else {
  122. _defer = fallback;
  123. }
  124. var setImmediate$1 = wrap(_defer);
  125. /**
  126. * Take a sync function and make it async, passing its return value to a
  127. * callback. This is useful for plugging sync functions into a waterfall,
  128. * series, or other async functions. Any arguments passed to the generated
  129. * function will be passed to the wrapped function (except for the final
  130. * callback argument). Errors thrown will be passed to the callback.
  131. *
  132. * If the function passed to `asyncify` returns a Promise, that promises's
  133. * resolved/rejected state will be used to call the callback, rather than simply
  134. * the synchronous return value.
  135. *
  136. * This also means you can asyncify ES2017 `async` functions.
  137. *
  138. * @name asyncify
  139. * @static
  140. * @memberOf module:Utils
  141. * @method
  142. * @alias wrapSync
  143. * @category Util
  144. * @param {Function} func - The synchronous function, or Promise-returning
  145. * function to convert to an {@link AsyncFunction}.
  146. * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
  147. * invoked with `(args..., callback)`.
  148. * @example
  149. *
  150. * // passing a regular synchronous function
  151. * async.waterfall([
  152. * async.apply(fs.readFile, filename, "utf8"),
  153. * async.asyncify(JSON.parse),
  154. * function (data, next) {
  155. * // data is the result of parsing the text.
  156. * // If there was a parsing error, it would have been caught.
  157. * }
  158. * ], callback);
  159. *
  160. * // passing a function returning a promise
  161. * async.waterfall([
  162. * async.apply(fs.readFile, filename, "utf8"),
  163. * async.asyncify(function (contents) {
  164. * return db.model.create(contents);
  165. * }),
  166. * function (model, next) {
  167. * // `model` is the instantiated model object.
  168. * // If there was an error, this function would be skipped.
  169. * }
  170. * ], callback);
  171. *
  172. * // es2017 example, though `asyncify` is not needed if your JS environment
  173. * // supports async functions out of the box
  174. * var q = async.queue(async.asyncify(async function(file) {
  175. * var intermediateStep = await processFile(file);
  176. * return await somePromise(intermediateStep)
  177. * }));
  178. *
  179. * q.push(files);
  180. */
  181. function asyncify(func) {
  182. return initialParams(function (args, callback) {
  183. var result;
  184. try {
  185. result = func.apply(this, args);
  186. } catch (e) {
  187. return callback(e);
  188. }
  189. // if result is Promise object
  190. if (isObject(result) && typeof result.then === 'function') {
  191. result.then(function(value) {
  192. invokeCallback(callback, null, value);
  193. }, function(err) {
  194. invokeCallback(callback, err.message ? err : new Error(err));
  195. });
  196. } else {
  197. callback(null, result);
  198. }
  199. });
  200. }
  201. function invokeCallback(callback, error, value) {
  202. try {
  203. callback(error, value);
  204. } catch (e) {
  205. setImmediate$1(rethrow, e);
  206. }
  207. }
  208. function rethrow(error) {
  209. throw error;
  210. }
  211. var supportsSymbol = typeof Symbol === 'function';
  212. function isAsync(fn) {
  213. return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction';
  214. }
  215. function wrapAsync(asyncFn) {
  216. return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;
  217. }
  218. function applyEach$1(eachfn) {
  219. return function(fns/*, ...args*/) {
  220. var args = slice(arguments, 1);
  221. var go = initialParams(function(args, callback) {
  222. var that = this;
  223. return eachfn(fns, function (fn, cb) {
  224. wrapAsync(fn).apply(that, args.concat(cb));
  225. }, callback);
  226. });
  227. if (args.length) {
  228. return go.apply(this, args);
  229. }
  230. else {
  231. return go;
  232. }
  233. };
  234. }
  235. /** Detect free variable `global` from Node.js. */
  236. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  237. /** Detect free variable `self`. */
  238. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  239. /** Used as a reference to the global object. */
  240. var root = freeGlobal || freeSelf || Function('return this')();
  241. /** Built-in value references. */
  242. var Symbol$1 = root.Symbol;
  243. /** Used for built-in method references. */
  244. var objectProto = Object.prototype;
  245. /** Used to check objects for own properties. */
  246. var hasOwnProperty = objectProto.hasOwnProperty;
  247. /**
  248. * Used to resolve the
  249. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  250. * of values.
  251. */
  252. var nativeObjectToString = objectProto.toString;
  253. /** Built-in value references. */
  254. var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;
  255. /**
  256. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  257. *
  258. * @private
  259. * @param {*} value The value to query.
  260. * @returns {string} Returns the raw `toStringTag`.
  261. */
  262. function getRawTag(value) {
  263. var isOwn = hasOwnProperty.call(value, symToStringTag$1),
  264. tag = value[symToStringTag$1];
  265. try {
  266. value[symToStringTag$1] = undefined;
  267. var unmasked = true;
  268. } catch (e) {}
  269. var result = nativeObjectToString.call(value);
  270. if (unmasked) {
  271. if (isOwn) {
  272. value[symToStringTag$1] = tag;
  273. } else {
  274. delete value[symToStringTag$1];
  275. }
  276. }
  277. return result;
  278. }
  279. /** Used for built-in method references. */
  280. var objectProto$1 = Object.prototype;
  281. /**
  282. * Used to resolve the
  283. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  284. * of values.
  285. */
  286. var nativeObjectToString$1 = objectProto$1.toString;
  287. /**
  288. * Converts `value` to a string using `Object.prototype.toString`.
  289. *
  290. * @private
  291. * @param {*} value The value to convert.
  292. * @returns {string} Returns the converted string.
  293. */
  294. function objectToString(value) {
  295. return nativeObjectToString$1.call(value);
  296. }
  297. /** `Object#toString` result references. */
  298. var nullTag = '[object Null]';
  299. var undefinedTag = '[object Undefined]';
  300. /** Built-in value references. */
  301. var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
  302. /**
  303. * The base implementation of `getTag` without fallbacks for buggy environments.
  304. *
  305. * @private
  306. * @param {*} value The value to query.
  307. * @returns {string} Returns the `toStringTag`.
  308. */
  309. function baseGetTag(value) {
  310. if (value == null) {
  311. return value === undefined ? undefinedTag : nullTag;
  312. }
  313. return (symToStringTag && symToStringTag in Object(value))
  314. ? getRawTag(value)
  315. : objectToString(value);
  316. }
  317. /** `Object#toString` result references. */
  318. var asyncTag = '[object AsyncFunction]';
  319. var funcTag = '[object Function]';
  320. var genTag = '[object GeneratorFunction]';
  321. var proxyTag = '[object Proxy]';
  322. /**
  323. * Checks if `value` is classified as a `Function` object.
  324. *
  325. * @static
  326. * @memberOf _
  327. * @since 0.1.0
  328. * @category Lang
  329. * @param {*} value The value to check.
  330. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  331. * @example
  332. *
  333. * _.isFunction(_);
  334. * // => true
  335. *
  336. * _.isFunction(/abc/);
  337. * // => false
  338. */
  339. function isFunction(value) {
  340. if (!isObject(value)) {
  341. return false;
  342. }
  343. // The use of `Object#toString` avoids issues with the `typeof` operator
  344. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  345. var tag = baseGetTag(value);
  346. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  347. }
  348. /** Used as references for various `Number` constants. */
  349. var MAX_SAFE_INTEGER = 9007199254740991;
  350. /**
  351. * Checks if `value` is a valid array-like length.
  352. *
  353. * **Note:** This method is loosely based on
  354. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  355. *
  356. * @static
  357. * @memberOf _
  358. * @since 4.0.0
  359. * @category Lang
  360. * @param {*} value The value to check.
  361. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  362. * @example
  363. *
  364. * _.isLength(3);
  365. * // => true
  366. *
  367. * _.isLength(Number.MIN_VALUE);
  368. * // => false
  369. *
  370. * _.isLength(Infinity);
  371. * // => false
  372. *
  373. * _.isLength('3');
  374. * // => false
  375. */
  376. function isLength(value) {
  377. return typeof value == 'number' &&
  378. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  379. }
  380. /**
  381. * Checks if `value` is array-like. A value is considered array-like if it's
  382. * not a function and has a `value.length` that's an integer greater than or
  383. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  384. *
  385. * @static
  386. * @memberOf _
  387. * @since 4.0.0
  388. * @category Lang
  389. * @param {*} value The value to check.
  390. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  391. * @example
  392. *
  393. * _.isArrayLike([1, 2, 3]);
  394. * // => true
  395. *
  396. * _.isArrayLike(document.body.children);
  397. * // => true
  398. *
  399. * _.isArrayLike('abc');
  400. * // => true
  401. *
  402. * _.isArrayLike(_.noop);
  403. * // => false
  404. */
  405. function isArrayLike(value) {
  406. return value != null && isLength(value.length) && !isFunction(value);
  407. }
  408. // A temporary value used to identify if the loop should be broken.
  409. // See #1064, #1293
  410. var breakLoop = {};
  411. /**
  412. * This method returns `undefined`.
  413. *
  414. * @static
  415. * @memberOf _
  416. * @since 2.3.0
  417. * @category Util
  418. * @example
  419. *
  420. * _.times(2, _.noop);
  421. * // => [undefined, undefined]
  422. */
  423. function noop() {
  424. // No operation performed.
  425. }
  426. function once(fn) {
  427. return function () {
  428. if (fn === null) return;
  429. var callFn = fn;
  430. fn = null;
  431. callFn.apply(this, arguments);
  432. };
  433. }
  434. var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator;
  435. var getIterator = function (coll) {
  436. return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol]();
  437. };
  438. /**
  439. * The base implementation of `_.times` without support for iteratee shorthands
  440. * or max array length checks.
  441. *
  442. * @private
  443. * @param {number} n The number of times to invoke `iteratee`.
  444. * @param {Function} iteratee The function invoked per iteration.
  445. * @returns {Array} Returns the array of results.
  446. */
  447. function baseTimes(n, iteratee) {
  448. var index = -1,
  449. result = Array(n);
  450. while (++index < n) {
  451. result[index] = iteratee(index);
  452. }
  453. return result;
  454. }
  455. /**
  456. * Checks if `value` is object-like. A value is object-like if it's not `null`
  457. * and has a `typeof` result of "object".
  458. *
  459. * @static
  460. * @memberOf _
  461. * @since 4.0.0
  462. * @category Lang
  463. * @param {*} value The value to check.
  464. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  465. * @example
  466. *
  467. * _.isObjectLike({});
  468. * // => true
  469. *
  470. * _.isObjectLike([1, 2, 3]);
  471. * // => true
  472. *
  473. * _.isObjectLike(_.noop);
  474. * // => false
  475. *
  476. * _.isObjectLike(null);
  477. * // => false
  478. */
  479. function isObjectLike(value) {
  480. return value != null && typeof value == 'object';
  481. }
  482. /** `Object#toString` result references. */
  483. var argsTag = '[object Arguments]';
  484. /**
  485. * The base implementation of `_.isArguments`.
  486. *
  487. * @private
  488. * @param {*} value The value to check.
  489. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  490. */
  491. function baseIsArguments(value) {
  492. return isObjectLike(value) && baseGetTag(value) == argsTag;
  493. }
  494. /** Used for built-in method references. */
  495. var objectProto$3 = Object.prototype;
  496. /** Used to check objects for own properties. */
  497. var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
  498. /** Built-in value references. */
  499. var propertyIsEnumerable = objectProto$3.propertyIsEnumerable;
  500. /**
  501. * Checks if `value` is likely an `arguments` object.
  502. *
  503. * @static
  504. * @memberOf _
  505. * @since 0.1.0
  506. * @category Lang
  507. * @param {*} value The value to check.
  508. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  509. * else `false`.
  510. * @example
  511. *
  512. * _.isArguments(function() { return arguments; }());
  513. * // => true
  514. *
  515. * _.isArguments([1, 2, 3]);
  516. * // => false
  517. */
  518. var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
  519. return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') &&
  520. !propertyIsEnumerable.call(value, 'callee');
  521. };
  522. /**
  523. * Checks if `value` is classified as an `Array` object.
  524. *
  525. * @static
  526. * @memberOf _
  527. * @since 0.1.0
  528. * @category Lang
  529. * @param {*} value The value to check.
  530. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  531. * @example
  532. *
  533. * _.isArray([1, 2, 3]);
  534. * // => true
  535. *
  536. * _.isArray(document.body.children);
  537. * // => false
  538. *
  539. * _.isArray('abc');
  540. * // => false
  541. *
  542. * _.isArray(_.noop);
  543. * // => false
  544. */
  545. var isArray = Array.isArray;
  546. /**
  547. * This method returns `false`.
  548. *
  549. * @static
  550. * @memberOf _
  551. * @since 4.13.0
  552. * @category Util
  553. * @returns {boolean} Returns `false`.
  554. * @example
  555. *
  556. * _.times(2, _.stubFalse);
  557. * // => [false, false]
  558. */
  559. function stubFalse() {
  560. return false;
  561. }
  562. /** Detect free variable `exports`. */
  563. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  564. /** Detect free variable `module`. */
  565. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  566. /** Detect the popular CommonJS extension `module.exports`. */
  567. var moduleExports = freeModule && freeModule.exports === freeExports;
  568. /** Built-in value references. */
  569. var Buffer = moduleExports ? root.Buffer : undefined;
  570. /* Built-in method references for those with the same name as other `lodash` methods. */
  571. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  572. /**
  573. * Checks if `value` is a buffer.
  574. *
  575. * @static
  576. * @memberOf _
  577. * @since 4.3.0
  578. * @category Lang
  579. * @param {*} value The value to check.
  580. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  581. * @example
  582. *
  583. * _.isBuffer(new Buffer(2));
  584. * // => true
  585. *
  586. * _.isBuffer(new Uint8Array(2));
  587. * // => false
  588. */
  589. var isBuffer = nativeIsBuffer || stubFalse;
  590. /** Used as references for various `Number` constants. */
  591. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  592. /** Used to detect unsigned integer values. */
  593. var reIsUint = /^(?:0|[1-9]\d*)$/;
  594. /**
  595. * Checks if `value` is a valid array-like index.
  596. *
  597. * @private
  598. * @param {*} value The value to check.
  599. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  600. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  601. */
  602. function isIndex(value, length) {
  603. var type = typeof value;
  604. length = length == null ? MAX_SAFE_INTEGER$1 : length;
  605. return !!length &&
  606. (type == 'number' ||
  607. (type != 'symbol' && reIsUint.test(value))) &&
  608. (value > -1 && value % 1 == 0 && value < length);
  609. }
  610. /** `Object#toString` result references. */
  611. var argsTag$1 = '[object Arguments]';
  612. var arrayTag = '[object Array]';
  613. var boolTag = '[object Boolean]';
  614. var dateTag = '[object Date]';
  615. var errorTag = '[object Error]';
  616. var funcTag$1 = '[object Function]';
  617. var mapTag = '[object Map]';
  618. var numberTag = '[object Number]';
  619. var objectTag = '[object Object]';
  620. var regexpTag = '[object RegExp]';
  621. var setTag = '[object Set]';
  622. var stringTag = '[object String]';
  623. var weakMapTag = '[object WeakMap]';
  624. var arrayBufferTag = '[object ArrayBuffer]';
  625. var dataViewTag = '[object DataView]';
  626. var float32Tag = '[object Float32Array]';
  627. var float64Tag = '[object Float64Array]';
  628. var int8Tag = '[object Int8Array]';
  629. var int16Tag = '[object Int16Array]';
  630. var int32Tag = '[object Int32Array]';
  631. var uint8Tag = '[object Uint8Array]';
  632. var uint8ClampedTag = '[object Uint8ClampedArray]';
  633. var uint16Tag = '[object Uint16Array]';
  634. var uint32Tag = '[object Uint32Array]';
  635. /** Used to identify `toStringTag` values of typed arrays. */
  636. var typedArrayTags = {};
  637. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  638. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  639. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  640. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  641. typedArrayTags[uint32Tag] = true;
  642. typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
  643. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  644. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  645. typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =
  646. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  647. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  648. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  649. typedArrayTags[weakMapTag] = false;
  650. /**
  651. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  652. *
  653. * @private
  654. * @param {*} value The value to check.
  655. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  656. */
  657. function baseIsTypedArray(value) {
  658. return isObjectLike(value) &&
  659. isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
  660. }
  661. /**
  662. * The base implementation of `_.unary` without support for storing metadata.
  663. *
  664. * @private
  665. * @param {Function} func The function to cap arguments for.
  666. * @returns {Function} Returns the new capped function.
  667. */
  668. function baseUnary(func) {
  669. return function(value) {
  670. return func(value);
  671. };
  672. }
  673. /** Detect free variable `exports`. */
  674. var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
  675. /** Detect free variable `module`. */
  676. var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
  677. /** Detect the popular CommonJS extension `module.exports`. */
  678. var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
  679. /** Detect free variable `process` from Node.js. */
  680. var freeProcess = moduleExports$1 && freeGlobal.process;
  681. /** Used to access faster Node.js helpers. */
  682. var nodeUtil = (function() {
  683. try {
  684. // Use `util.types` for Node.js 10+.
  685. var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types;
  686. if (types) {
  687. return types;
  688. }
  689. // Legacy `process.binding('util')` for Node.js < 10.
  690. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  691. } catch (e) {}
  692. }());
  693. /* Node.js helper references. */
  694. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  695. /**
  696. * Checks if `value` is classified as a typed array.
  697. *
  698. * @static
  699. * @memberOf _
  700. * @since 3.0.0
  701. * @category Lang
  702. * @param {*} value The value to check.
  703. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  704. * @example
  705. *
  706. * _.isTypedArray(new Uint8Array);
  707. * // => true
  708. *
  709. * _.isTypedArray([]);
  710. * // => false
  711. */
  712. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  713. /** Used for built-in method references. */
  714. var objectProto$2 = Object.prototype;
  715. /** Used to check objects for own properties. */
  716. var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
  717. /**
  718. * Creates an array of the enumerable property names of the array-like `value`.
  719. *
  720. * @private
  721. * @param {*} value The value to query.
  722. * @param {boolean} inherited Specify returning inherited property names.
  723. * @returns {Array} Returns the array of property names.
  724. */
  725. function arrayLikeKeys(value, inherited) {
  726. var isArr = isArray(value),
  727. isArg = !isArr && isArguments(value),
  728. isBuff = !isArr && !isArg && isBuffer(value),
  729. isType = !isArr && !isArg && !isBuff && isTypedArray(value),
  730. skipIndexes = isArr || isArg || isBuff || isType,
  731. result = skipIndexes ? baseTimes(value.length, String) : [],
  732. length = result.length;
  733. for (var key in value) {
  734. if ((inherited || hasOwnProperty$1.call(value, key)) &&
  735. !(skipIndexes && (
  736. // Safari 9 has enumerable `arguments.length` in strict mode.
  737. key == 'length' ||
  738. // Node.js 0.10 has enumerable non-index properties on buffers.
  739. (isBuff && (key == 'offset' || key == 'parent')) ||
  740. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  741. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  742. // Skip index properties.
  743. isIndex(key, length)
  744. ))) {
  745. result.push(key);
  746. }
  747. }
  748. return result;
  749. }
  750. /** Used for built-in method references. */
  751. var objectProto$5 = Object.prototype;
  752. /**
  753. * Checks if `value` is likely a prototype object.
  754. *
  755. * @private
  756. * @param {*} value The value to check.
  757. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  758. */
  759. function isPrototype(value) {
  760. var Ctor = value && value.constructor,
  761. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5;
  762. return value === proto;
  763. }
  764. /**
  765. * Creates a unary function that invokes `func` with its argument transformed.
  766. *
  767. * @private
  768. * @param {Function} func The function to wrap.
  769. * @param {Function} transform The argument transform.
  770. * @returns {Function} Returns the new function.
  771. */
  772. function overArg(func, transform) {
  773. return function(arg) {
  774. return func(transform(arg));
  775. };
  776. }
  777. /* Built-in method references for those with the same name as other `lodash` methods. */
  778. var nativeKeys = overArg(Object.keys, Object);
  779. /** Used for built-in method references. */
  780. var objectProto$4 = Object.prototype;
  781. /** Used to check objects for own properties. */
  782. var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
  783. /**
  784. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  785. *
  786. * @private
  787. * @param {Object} object The object to query.
  788. * @returns {Array} Returns the array of property names.
  789. */
  790. function baseKeys(object) {
  791. if (!isPrototype(object)) {
  792. return nativeKeys(object);
  793. }
  794. var result = [];
  795. for (var key in Object(object)) {
  796. if (hasOwnProperty$3.call(object, key) && key != 'constructor') {
  797. result.push(key);
  798. }
  799. }
  800. return result;
  801. }
  802. /**
  803. * Creates an array of the own enumerable property names of `object`.
  804. *
  805. * **Note:** Non-object values are coerced to objects. See the
  806. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  807. * for more details.
  808. *
  809. * @static
  810. * @since 0.1.0
  811. * @memberOf _
  812. * @category Object
  813. * @param {Object} object The object to query.
  814. * @returns {Array} Returns the array of property names.
  815. * @example
  816. *
  817. * function Foo() {
  818. * this.a = 1;
  819. * this.b = 2;
  820. * }
  821. *
  822. * Foo.prototype.c = 3;
  823. *
  824. * _.keys(new Foo);
  825. * // => ['a', 'b'] (iteration order is not guaranteed)
  826. *
  827. * _.keys('hi');
  828. * // => ['0', '1']
  829. */
  830. function keys(object) {
  831. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  832. }
  833. function createArrayIterator(coll) {
  834. var i = -1;
  835. var len = coll.length;
  836. return function next() {
  837. return ++i < len ? {value: coll[i], key: i} : null;
  838. }
  839. }
  840. function createES2015Iterator(iterator) {
  841. var i = -1;
  842. return function next() {
  843. var item = iterator.next();
  844. if (item.done)
  845. return null;
  846. i++;
  847. return {value: item.value, key: i};
  848. }
  849. }
  850. function createObjectIterator(obj) {
  851. var okeys = keys(obj);
  852. var i = -1;
  853. var len = okeys.length;
  854. return function next() {
  855. var key = okeys[++i];
  856. return i < len ? {value: obj[key], key: key} : null;
  857. };
  858. }
  859. function iterator(coll) {
  860. if (isArrayLike(coll)) {
  861. return createArrayIterator(coll);
  862. }
  863. var iterator = getIterator(coll);
  864. return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
  865. }
  866. function onlyOnce(fn) {
  867. return function() {
  868. if (fn === null) throw new Error("Callback was already called.");
  869. var callFn = fn;
  870. fn = null;
  871. callFn.apply(this, arguments);
  872. };
  873. }
  874. function _eachOfLimit(limit) {
  875. return function (obj, iteratee, callback) {
  876. callback = once(callback || noop);
  877. if (limit <= 0 || !obj) {
  878. return callback(null);
  879. }
  880. var nextElem = iterator(obj);
  881. var done = false;
  882. var running = 0;
  883. var looping = false;
  884. function iterateeCallback(err, value) {
  885. running -= 1;
  886. if (err) {
  887. done = true;
  888. callback(err);
  889. }
  890. else if (value === breakLoop || (done && running <= 0)) {
  891. done = true;
  892. return callback(null);
  893. }
  894. else if (!looping) {
  895. replenish();
  896. }
  897. }
  898. function replenish () {
  899. looping = true;
  900. while (running < limit && !done) {
  901. var elem = nextElem();
  902. if (elem === null) {
  903. done = true;
  904. if (running <= 0) {
  905. callback(null);
  906. }
  907. return;
  908. }
  909. running += 1;
  910. iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
  911. }
  912. looping = false;
  913. }
  914. replenish();
  915. };
  916. }
  917. /**
  918. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
  919. * time.
  920. *
  921. * @name eachOfLimit
  922. * @static
  923. * @memberOf module:Collections
  924. * @method
  925. * @see [async.eachOf]{@link module:Collections.eachOf}
  926. * @alias forEachOfLimit
  927. * @category Collection
  928. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  929. * @param {number} limit - The maximum number of async operations at a time.
  930. * @param {AsyncFunction} iteratee - An async function to apply to each
  931. * item in `coll`. The `key` is the item's key, or index in the case of an
  932. * array.
  933. * Invoked with (item, key, callback).
  934. * @param {Function} [callback] - A callback which is called when all
  935. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  936. */
  937. function eachOfLimit(coll, limit, iteratee, callback) {
  938. _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);
  939. }
  940. function doLimit(fn, limit) {
  941. return function (iterable, iteratee, callback) {
  942. return fn(iterable, limit, iteratee, callback);
  943. };
  944. }
  945. // eachOf implementation optimized for array-likes
  946. function eachOfArrayLike(coll, iteratee, callback) {
  947. callback = once(callback || noop);
  948. var index = 0,
  949. completed = 0,
  950. length = coll.length;
  951. if (length === 0) {
  952. callback(null);
  953. }
  954. function iteratorCallback(err, value) {
  955. if (err) {
  956. callback(err);
  957. } else if ((++completed === length) || value === breakLoop) {
  958. callback(null);
  959. }
  960. }
  961. for (; index < length; index++) {
  962. iteratee(coll[index], index, onlyOnce(iteratorCallback));
  963. }
  964. }
  965. // a generic version of eachOf which can handle array, object, and iterator cases.
  966. var eachOfGeneric = doLimit(eachOfLimit, Infinity);
  967. /**
  968. * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
  969. * to the iteratee.
  970. *
  971. * @name eachOf
  972. * @static
  973. * @memberOf module:Collections
  974. * @method
  975. * @alias forEachOf
  976. * @category Collection
  977. * @see [async.each]{@link module:Collections.each}
  978. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  979. * @param {AsyncFunction} iteratee - A function to apply to each
  980. * item in `coll`.
  981. * The `key` is the item's key, or index in the case of an array.
  982. * Invoked with (item, key, callback).
  983. * @param {Function} [callback] - A callback which is called when all
  984. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  985. * @example
  986. *
  987. * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
  988. * var configs = {};
  989. *
  990. * async.forEachOf(obj, function (value, key, callback) {
  991. * fs.readFile(__dirname + value, "utf8", function (err, data) {
  992. * if (err) return callback(err);
  993. * try {
  994. * configs[key] = JSON.parse(data);
  995. * } catch (e) {
  996. * return callback(e);
  997. * }
  998. * callback();
  999. * });
  1000. * }, function (err) {
  1001. * if (err) console.error(err.message);
  1002. * // configs is now a map of JSON data
  1003. * doSomethingWith(configs);
  1004. * });
  1005. */
  1006. var eachOf = function(coll, iteratee, callback) {
  1007. var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
  1008. eachOfImplementation(coll, wrapAsync(iteratee), callback);
  1009. };
  1010. function doParallel(fn) {
  1011. return function (obj, iteratee, callback) {
  1012. return fn(eachOf, obj, wrapAsync(iteratee), callback);
  1013. };
  1014. }
  1015. function _asyncMap(eachfn, arr, iteratee, callback) {
  1016. callback = callback || noop;
  1017. arr = arr || [];
  1018. var results = [];
  1019. var counter = 0;
  1020. var _iteratee = wrapAsync(iteratee);
  1021. eachfn(arr, function (value, _, callback) {
  1022. var index = counter++;
  1023. _iteratee(value, function (err, v) {
  1024. results[index] = v;
  1025. callback(err);
  1026. });
  1027. }, function (err) {
  1028. callback(err, results);
  1029. });
  1030. }
  1031. /**
  1032. * Produces a new collection of values by mapping each value in `coll` through
  1033. * the `iteratee` function. The `iteratee` is called with an item from `coll`
  1034. * and a callback for when it has finished processing. Each of these callback
  1035. * takes 2 arguments: an `error`, and the transformed item from `coll`. If
  1036. * `iteratee` passes an error to its callback, the main `callback` (for the
  1037. * `map` function) is immediately called with the error.
  1038. *
  1039. * Note, that since this function applies the `iteratee` to each item in
  1040. * parallel, there is no guarantee that the `iteratee` functions will complete
  1041. * in order. However, the results array will be in the same order as the
  1042. * original `coll`.
  1043. *
  1044. * If `map` is passed an Object, the results will be an Array. The results
  1045. * will roughly be in the order of the original Objects' keys (but this can
  1046. * vary across JavaScript engines).
  1047. *
  1048. * @name map
  1049. * @static
  1050. * @memberOf module:Collections
  1051. * @method
  1052. * @category Collection
  1053. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  1054. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  1055. * `coll`.
  1056. * The iteratee should complete with the transformed item.
  1057. * Invoked with (item, callback).
  1058. * @param {Function} [callback] - A callback which is called when all `iteratee`
  1059. * functions have finished, or an error occurs. Results is an Array of the
  1060. * transformed items from the `coll`. Invoked with (err, results).
  1061. * @example
  1062. *
  1063. * async.map(['file1','file2','file3'], fs.stat, function(err, results) {
  1064. * // results is now an array of stats for each file
  1065. * });
  1066. */
  1067. var map = doParallel(_asyncMap);
  1068. /**
  1069. * Applies the provided arguments to each function in the array, calling
  1070. * `callback` after all functions have completed. If you only provide the first
  1071. * argument, `fns`, then it will return a function which lets you pass in the
  1072. * arguments as if it were a single function call. If more arguments are
  1073. * provided, `callback` is required while `args` is still optional.
  1074. *
  1075. * @name applyEach
  1076. * @static
  1077. * @memberOf module:ControlFlow
  1078. * @method
  1079. * @category Control Flow
  1080. * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s
  1081. * to all call with the same arguments
  1082. * @param {...*} [args] - any number of separate arguments to pass to the
  1083. * function.
  1084. * @param {Function} [callback] - the final argument should be the callback,
  1085. * called when all functions have completed processing.
  1086. * @returns {Function} - If only the first argument, `fns`, is provided, it will
  1087. * return a function which lets you pass in the arguments as if it were a single
  1088. * function call. The signature is `(..args, callback)`. If invoked with any
  1089. * arguments, `callback` is required.
  1090. * @example
  1091. *
  1092. * async.applyEach([enableSearch, updateSchema], 'bucket', callback);
  1093. *
  1094. * // partial application example:
  1095. * async.each(
  1096. * buckets,
  1097. * async.applyEach([enableSearch, updateSchema]),
  1098. * callback
  1099. * );
  1100. */
  1101. var applyEach = applyEach$1(map);
  1102. function doParallelLimit(fn) {
  1103. return function (obj, limit, iteratee, callback) {
  1104. return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback);
  1105. };
  1106. }
  1107. /**
  1108. * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.
  1109. *
  1110. * @name mapLimit
  1111. * @static
  1112. * @memberOf module:Collections
  1113. * @method
  1114. * @see [async.map]{@link module:Collections.map}
  1115. * @category Collection
  1116. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  1117. * @param {number} limit - The maximum number of async operations at a time.
  1118. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  1119. * `coll`.
  1120. * The iteratee should complete with the transformed item.
  1121. * Invoked with (item, callback).
  1122. * @param {Function} [callback] - A callback which is called when all `iteratee`
  1123. * functions have finished, or an error occurs. Results is an array of the
  1124. * transformed items from the `coll`. Invoked with (err, results).
  1125. */
  1126. var mapLimit = doParallelLimit(_asyncMap);
  1127. /**
  1128. * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
  1129. *
  1130. * @name mapSeries
  1131. * @static
  1132. * @memberOf module:Collections
  1133. * @method
  1134. * @see [async.map]{@link module:Collections.map}
  1135. * @category Collection
  1136. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  1137. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  1138. * `coll`.
  1139. * The iteratee should complete with the transformed item.
  1140. * Invoked with (item, callback).
  1141. * @param {Function} [callback] - A callback which is called when all `iteratee`
  1142. * functions have finished, or an error occurs. Results is an array of the
  1143. * transformed items from the `coll`. Invoked with (err, results).
  1144. */
  1145. var mapSeries = doLimit(mapLimit, 1);
  1146. /**
  1147. * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.
  1148. *
  1149. * @name applyEachSeries
  1150. * @static
  1151. * @memberOf module:ControlFlow
  1152. * @method
  1153. * @see [async.applyEach]{@link module:ControlFlow.applyEach}
  1154. * @category Control Flow
  1155. * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all
  1156. * call with the same arguments
  1157. * @param {...*} [args] - any number of separate arguments to pass to the
  1158. * function.
  1159. * @param {Function} [callback] - the final argument should be the callback,
  1160. * called when all functions have completed processing.
  1161. * @returns {Function} - If only the first argument is provided, it will return
  1162. * a function which lets you pass in the arguments as if it were a single
  1163. * function call.
  1164. */
  1165. var applyEachSeries = applyEach$1(mapSeries);
  1166. /**
  1167. * A specialized version of `_.forEach` for arrays without support for
  1168. * iteratee shorthands.
  1169. *
  1170. * @private
  1171. * @param {Array} [array] The array to iterate over.
  1172. * @param {Function} iteratee The function invoked per iteration.
  1173. * @returns {Array} Returns `array`.
  1174. */
  1175. function arrayEach(array, iteratee) {
  1176. var index = -1,
  1177. length = array == null ? 0 : array.length;
  1178. while (++index < length) {
  1179. if (iteratee(array[index], index, array) === false) {
  1180. break;
  1181. }
  1182. }
  1183. return array;
  1184. }
  1185. /**
  1186. * Creates a base function for methods like `_.forIn` and `_.forOwn`.
  1187. *
  1188. * @private
  1189. * @param {boolean} [fromRight] Specify iterating from right to left.
  1190. * @returns {Function} Returns the new base function.
  1191. */
  1192. function createBaseFor(fromRight) {
  1193. return function(object, iteratee, keysFunc) {
  1194. var index = -1,
  1195. iterable = Object(object),
  1196. props = keysFunc(object),
  1197. length = props.length;
  1198. while (length--) {
  1199. var key = props[fromRight ? length : ++index];
  1200. if (iteratee(iterable[key], key, iterable) === false) {
  1201. break;
  1202. }
  1203. }
  1204. return object;
  1205. };
  1206. }
  1207. /**
  1208. * The base implementation of `baseForOwn` which iterates over `object`
  1209. * properties returned by `keysFunc` and invokes `iteratee` for each property.
  1210. * Iteratee functions may exit iteration early by explicitly returning `false`.
  1211. *
  1212. * @private
  1213. * @param {Object} object The object to iterate over.
  1214. * @param {Function} iteratee The function invoked per iteration.
  1215. * @param {Function} keysFunc The function to get the keys of `object`.
  1216. * @returns {Object} Returns `object`.
  1217. */
  1218. var baseFor = createBaseFor();
  1219. /**
  1220. * The base implementation of `_.forOwn` without support for iteratee shorthands.
  1221. *
  1222. * @private
  1223. * @param {Object} object The object to iterate over.
  1224. * @param {Function} iteratee The function invoked per iteration.
  1225. * @returns {Object} Returns `object`.
  1226. */
  1227. function baseForOwn(object, iteratee) {
  1228. return object && baseFor(object, iteratee, keys);
  1229. }
  1230. /**
  1231. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  1232. * support for iteratee shorthands.
  1233. *
  1234. * @private
  1235. * @param {Array} array The array to inspect.
  1236. * @param {Function} predicate The function invoked per iteration.
  1237. * @param {number} fromIndex The index to search from.
  1238. * @param {boolean} [fromRight] Specify iterating from right to left.
  1239. * @returns {number} Returns the index of the matched value, else `-1`.
  1240. */
  1241. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  1242. var length = array.length,
  1243. index = fromIndex + (fromRight ? 1 : -1);
  1244. while ((fromRight ? index-- : ++index < length)) {
  1245. if (predicate(array[index], index, array)) {
  1246. return index;
  1247. }
  1248. }
  1249. return -1;
  1250. }
  1251. /**
  1252. * The base implementation of `_.isNaN` without support for number objects.
  1253. *
  1254. * @private
  1255. * @param {*} value The value to check.
  1256. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  1257. */
  1258. function baseIsNaN(value) {
  1259. return value !== value;
  1260. }
  1261. /**
  1262. * A specialized version of `_.indexOf` which performs strict equality
  1263. * comparisons of values, i.e. `===`.
  1264. *
  1265. * @private
  1266. * @param {Array} array The array to inspect.
  1267. * @param {*} value The value to search for.
  1268. * @param {number} fromIndex The index to search from.
  1269. * @returns {number} Returns the index of the matched value, else `-1`.
  1270. */
  1271. function strictIndexOf(array, value, fromIndex) {
  1272. var index = fromIndex - 1,
  1273. length = array.length;
  1274. while (++index < length) {
  1275. if (array[index] === value) {
  1276. return index;
  1277. }
  1278. }
  1279. return -1;
  1280. }
  1281. /**
  1282. * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
  1283. *
  1284. * @private
  1285. * @param {Array} array The array to inspect.
  1286. * @param {*} value The value to search for.
  1287. * @param {number} fromIndex The index to search from.
  1288. * @returns {number} Returns the index of the matched value, else `-1`.
  1289. */
  1290. function baseIndexOf(array, value, fromIndex) {
  1291. return value === value
  1292. ? strictIndexOf(array, value, fromIndex)
  1293. : baseFindIndex(array, baseIsNaN, fromIndex);
  1294. }
  1295. /**
  1296. * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on
  1297. * their requirements. Each function can optionally depend on other functions
  1298. * being completed first, and each function is run as soon as its requirements
  1299. * are satisfied.
  1300. *
  1301. * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence
  1302. * will stop. Further tasks will not execute (so any other functions depending
  1303. * on it will not run), and the main `callback` is immediately called with the
  1304. * error.
  1305. *
  1306. * {@link AsyncFunction}s also receive an object containing the results of functions which
  1307. * have completed so far as the first argument, if they have dependencies. If a
  1308. * task function has no dependencies, it will only be passed a callback.
  1309. *
  1310. * @name auto
  1311. * @static
  1312. * @memberOf module:ControlFlow
  1313. * @method
  1314. * @category Control Flow
  1315. * @param {Object} tasks - An object. Each of its properties is either a
  1316. * function or an array of requirements, with the {@link AsyncFunction} itself the last item
  1317. * in the array. The object's key of a property serves as the name of the task
  1318. * defined by that property, i.e. can be used when specifying requirements for
  1319. * other tasks. The function receives one or two arguments:
  1320. * * a `results` object, containing the results of the previously executed
  1321. * functions, only passed if the task has any dependencies,
  1322. * * a `callback(err, result)` function, which must be called when finished,
  1323. * passing an `error` (which can be `null`) and the result of the function's
  1324. * execution.
  1325. * @param {number} [concurrency=Infinity] - An optional `integer` for
  1326. * determining the maximum number of tasks that can be run in parallel. By
  1327. * default, as many as possible.
  1328. * @param {Function} [callback] - An optional callback which is called when all
  1329. * the tasks have been completed. It receives the `err` argument if any `tasks`
  1330. * pass an error to their callback. Results are always returned; however, if an
  1331. * error occurs, no further `tasks` will be performed, and the results object
  1332. * will only contain partial results. Invoked with (err, results).
  1333. * @returns undefined
  1334. * @example
  1335. *
  1336. * async.auto({
  1337. * // this function will just be passed a callback
  1338. * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
  1339. * showData: ['readData', function(results, cb) {
  1340. * // results.readData is the file's contents
  1341. * // ...
  1342. * }]
  1343. * }, callback);
  1344. *
  1345. * async.auto({
  1346. * get_data: function(callback) {
  1347. * console.log('in get_data');
  1348. * // async code to get some data
  1349. * callback(null, 'data', 'converted to array');
  1350. * },
  1351. * make_folder: function(callback) {
  1352. * console.log('in make_folder');
  1353. * // async code to create a directory to store a file in
  1354. * // this is run at the same time as getting the data
  1355. * callback(null, 'folder');
  1356. * },
  1357. * write_file: ['get_data', 'make_folder', function(results, callback) {
  1358. * console.log('in write_file', JSON.stringify(results));
  1359. * // once there is some data and the directory exists,
  1360. * // write the data to a file in the directory
  1361. * callback(null, 'filename');
  1362. * }],
  1363. * email_link: ['write_file', function(results, callback) {
  1364. * console.log('in email_link', JSON.stringify(results));
  1365. * // once the file is written let's email a link to it...
  1366. * // results.write_file contains the filename returned by write_file.
  1367. * callback(null, {'file':results.write_file, 'email':'user@example.com'});
  1368. * }]
  1369. * }, function(err, results) {
  1370. * console.log('err = ', err);
  1371. * console.log('results = ', results);
  1372. * });
  1373. */
  1374. var auto = function (tasks, concurrency, callback) {
  1375. if (typeof concurrency === 'function') {
  1376. // concurrency is optional, shift the args.
  1377. callback = concurrency;
  1378. concurrency = null;
  1379. }
  1380. callback = once(callback || noop);
  1381. var keys$$1 = keys(tasks);
  1382. var numTasks = keys$$1.length;
  1383. if (!numTasks) {
  1384. return callback(null);
  1385. }
  1386. if (!concurrency) {
  1387. concurrency = numTasks;
  1388. }
  1389. var results = {};
  1390. var runningTasks = 0;
  1391. var hasError = false;
  1392. var listeners = Object.create(null);
  1393. var readyTasks = [];
  1394. // for cycle detection:
  1395. var readyToCheck = []; // tasks that have been identified as reachable
  1396. // without the possibility of returning to an ancestor task
  1397. var uncheckedDependencies = {};
  1398. baseForOwn(tasks, function (task, key) {
  1399. if (!isArray(task)) {
  1400. // no dependencies
  1401. enqueueTask(key, [task]);
  1402. readyToCheck.push(key);
  1403. return;
  1404. }
  1405. var dependencies = task.slice(0, task.length - 1);
  1406. var remainingDependencies = dependencies.length;
  1407. if (remainingDependencies === 0) {
  1408. enqueueTask(key, task);
  1409. readyToCheck.push(key);
  1410. return;
  1411. }
  1412. uncheckedDependencies[key] = remainingDependencies;
  1413. arrayEach(dependencies, function (dependencyName) {
  1414. if (!tasks[dependencyName]) {
  1415. throw new Error('async.auto task `' + key +
  1416. '` has a non-existent dependency `' +
  1417. dependencyName + '` in ' +
  1418. dependencies.join(', '));
  1419. }
  1420. addListener(dependencyName, function () {
  1421. remainingDependencies--;
  1422. if (remainingDependencies === 0) {
  1423. enqueueTask(key, task);
  1424. }
  1425. });
  1426. });
  1427. });
  1428. checkForDeadlocks();
  1429. processQueue();
  1430. function enqueueTask(key, task) {
  1431. readyTasks.push(function () {
  1432. runTask(key, task);
  1433. });
  1434. }
  1435. function processQueue() {
  1436. if (readyTasks.length === 0 && runningTasks === 0) {
  1437. return callback(null, results);
  1438. }
  1439. while(readyTasks.length && runningTasks < concurrency) {
  1440. var run = readyTasks.shift();
  1441. run();
  1442. }
  1443. }
  1444. function addListener(taskName, fn) {
  1445. var taskListeners = listeners[taskName];
  1446. if (!taskListeners) {
  1447. taskListeners = listeners[taskName] = [];
  1448. }
  1449. taskListeners.push(fn);
  1450. }
  1451. function taskComplete(taskName) {
  1452. var taskListeners = listeners[taskName] || [];
  1453. arrayEach(taskListeners, function (fn) {
  1454. fn();
  1455. });
  1456. processQueue();
  1457. }
  1458. function runTask(key, task) {
  1459. if (hasError) return;
  1460. var taskCallback = onlyOnce(function(err, result) {
  1461. runningTasks--;
  1462. if (arguments.length > 2) {
  1463. result = slice(arguments, 1);
  1464. }
  1465. if (err) {
  1466. var safeResults = {};
  1467. baseForOwn(results, function(val, rkey) {
  1468. safeResults[rkey] = val;
  1469. });
  1470. safeResults[key] = result;
  1471. hasError = true;
  1472. listeners = Object.create(null);
  1473. callback(err, safeResults);
  1474. } else {
  1475. results[key] = result;
  1476. taskComplete(key);
  1477. }
  1478. });
  1479. runningTasks++;
  1480. var taskFn = wrapAsync(task[task.length - 1]);
  1481. if (task.length > 1) {
  1482. taskFn(results, taskCallback);
  1483. } else {
  1484. taskFn(taskCallback);
  1485. }
  1486. }
  1487. function checkForDeadlocks() {
  1488. // Kahn's algorithm
  1489. // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm
  1490. // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html
  1491. var currentTask;
  1492. var counter = 0;
  1493. while (readyToCheck.length) {
  1494. currentTask = readyToCheck.pop();
  1495. counter++;
  1496. arrayEach(getDependents(currentTask), function (dependent) {
  1497. if (--uncheckedDependencies[dependent] === 0) {
  1498. readyToCheck.push(dependent);
  1499. }
  1500. });
  1501. }
  1502. if (counter !== numTasks) {
  1503. throw new Error(
  1504. 'async.auto cannot execute tasks due to a recursive dependency'
  1505. );
  1506. }
  1507. }
  1508. function getDependents(taskName) {
  1509. var result = [];
  1510. baseForOwn(tasks, function (task, key) {
  1511. if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) {
  1512. result.push(key);
  1513. }
  1514. });
  1515. return result;
  1516. }
  1517. };
  1518. /**
  1519. * A specialized version of `_.map` for arrays without support for iteratee
  1520. * shorthands.
  1521. *
  1522. * @private
  1523. * @param {Array} [array] The array to iterate over.
  1524. * @param {Function} iteratee The function invoked per iteration.
  1525. * @returns {Array} Returns the new mapped array.
  1526. */
  1527. function arrayMap(array, iteratee) {
  1528. var index = -1,
  1529. length = array == null ? 0 : array.length,
  1530. result = Array(length);
  1531. while (++index < length) {
  1532. result[index] = iteratee(array[index], index, array);
  1533. }
  1534. return result;
  1535. }
  1536. /** `Object#toString` result references. */
  1537. var symbolTag = '[object Symbol]';
  1538. /**
  1539. * Checks if `value` is classified as a `Symbol` primitive or object.
  1540. *
  1541. * @static
  1542. * @memberOf _
  1543. * @since 4.0.0
  1544. * @category Lang
  1545. * @param {*} value The value to check.
  1546. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  1547. * @example
  1548. *
  1549. * _.isSymbol(Symbol.iterator);
  1550. * // => true
  1551. *
  1552. * _.isSymbol('abc');
  1553. * // => false
  1554. */
  1555. function isSymbol(value) {
  1556. return typeof value == 'symbol' ||
  1557. (isObjectLike(value) && baseGetTag(value) == symbolTag);
  1558. }
  1559. /** Used as references for various `Number` constants. */
  1560. var INFINITY = 1 / 0;
  1561. /** Used to convert symbols to primitives and strings. */
  1562. var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined;
  1563. var symbolToString = symbolProto ? symbolProto.toString : undefined;
  1564. /**
  1565. * The base implementation of `_.toString` which doesn't convert nullish
  1566. * values to empty strings.
  1567. *
  1568. * @private
  1569. * @param {*} value The value to process.
  1570. * @returns {string} Returns the string.
  1571. */
  1572. function baseToString(value) {
  1573. // Exit early for strings to avoid a performance hit in some environments.
  1574. if (typeof value == 'string') {
  1575. return value;
  1576. }
  1577. if (isArray(value)) {
  1578. // Recursively convert values (susceptible to call stack limits).
  1579. return arrayMap(value, baseToString) + '';
  1580. }
  1581. if (isSymbol(value)) {
  1582. return symbolToString ? symbolToString.call(value) : '';
  1583. }
  1584. var result = (value + '');
  1585. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  1586. }
  1587. /**
  1588. * The base implementation of `_.slice` without an iteratee call guard.
  1589. *
  1590. * @private
  1591. * @param {Array} array The array to slice.
  1592. * @param {number} [start=0] The start position.
  1593. * @param {number} [end=array.length] The end position.
  1594. * @returns {Array} Returns the slice of `array`.
  1595. */
  1596. function baseSlice(array, start, end) {
  1597. var index = -1,
  1598. length = array.length;
  1599. if (start < 0) {
  1600. start = -start > length ? 0 : (length + start);
  1601. }
  1602. end = end > length ? length : end;
  1603. if (end < 0) {
  1604. end += length;
  1605. }
  1606. length = start > end ? 0 : ((end - start) >>> 0);
  1607. start >>>= 0;
  1608. var result = Array(length);
  1609. while (++index < length) {
  1610. result[index] = array[index + start];
  1611. }
  1612. return result;
  1613. }
  1614. /**
  1615. * Casts `array` to a slice if it's needed.
  1616. *
  1617. * @private
  1618. * @param {Array} array The array to inspect.
  1619. * @param {number} start The start position.
  1620. * @param {number} [end=array.length] The end position.
  1621. * @returns {Array} Returns the cast slice.
  1622. */
  1623. function castSlice(array, start, end) {
  1624. var length = array.length;
  1625. end = end === undefined ? length : end;
  1626. return (!start && end >= length) ? array : baseSlice(array, start, end);
  1627. }
  1628. /**
  1629. * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
  1630. * that is not found in the character symbols.
  1631. *
  1632. * @private
  1633. * @param {Array} strSymbols The string symbols to inspect.
  1634. * @param {Array} chrSymbols The character symbols to find.
  1635. * @returns {number} Returns the index of the last unmatched string symbol.
  1636. */
  1637. function charsEndIndex(strSymbols, chrSymbols) {
  1638. var index = strSymbols.length;
  1639. while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
  1640. return index;
  1641. }
  1642. /**
  1643. * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
  1644. * that is not found in the character symbols.
  1645. *
  1646. * @private
  1647. * @param {Array} strSymbols The string symbols to inspect.
  1648. * @param {Array} chrSymbols The character symbols to find.
  1649. * @returns {number} Returns the index of the first unmatched string symbol.
  1650. */
  1651. function charsStartIndex(strSymbols, chrSymbols) {
  1652. var index = -1,
  1653. length = strSymbols.length;
  1654. while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
  1655. return index;
  1656. }
  1657. /**
  1658. * Converts an ASCII `string` to an array.
  1659. *
  1660. * @private
  1661. * @param {string} string The string to convert.
  1662. * @returns {Array} Returns the converted array.
  1663. */
  1664. function asciiToArray(string) {
  1665. return string.split('');
  1666. }
  1667. /** Used to compose unicode character classes. */
  1668. var rsAstralRange = '\\ud800-\\udfff';
  1669. var rsComboMarksRange = '\\u0300-\\u036f';
  1670. var reComboHalfMarksRange = '\\ufe20-\\ufe2f';
  1671. var rsComboSymbolsRange = '\\u20d0-\\u20ff';
  1672. var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;
  1673. var rsVarRange = '\\ufe0e\\ufe0f';
  1674. /** Used to compose unicode capture groups. */
  1675. var rsZWJ = '\\u200d';
  1676. /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
  1677. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
  1678. /**
  1679. * Checks if `string` contains Unicode symbols.
  1680. *
  1681. * @private
  1682. * @param {string} string The string to inspect.
  1683. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  1684. */
  1685. function hasUnicode(string) {
  1686. return reHasUnicode.test(string);
  1687. }
  1688. /** Used to compose unicode character classes. */
  1689. var rsAstralRange$1 = '\\ud800-\\udfff';
  1690. var rsComboMarksRange$1 = '\\u0300-\\u036f';
  1691. var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f';
  1692. var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff';
  1693. var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1;
  1694. var rsVarRange$1 = '\\ufe0e\\ufe0f';
  1695. /** Used to compose unicode capture groups. */
  1696. var rsAstral = '[' + rsAstralRange$1 + ']';
  1697. var rsCombo = '[' + rsComboRange$1 + ']';
  1698. var rsFitz = '\\ud83c[\\udffb-\\udfff]';
  1699. var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')';
  1700. var rsNonAstral = '[^' + rsAstralRange$1 + ']';
  1701. var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}';
  1702. var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]';
  1703. var rsZWJ$1 = '\\u200d';
  1704. /** Used to compose unicode regexes. */
  1705. var reOptMod = rsModifier + '?';
  1706. var rsOptVar = '[' + rsVarRange$1 + ']?';
  1707. var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*';
  1708. var rsSeq = rsOptVar + reOptMod + rsOptJoin;
  1709. var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  1710. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  1711. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  1712. /**
  1713. * Converts a Unicode `string` to an array.
  1714. *
  1715. * @private
  1716. * @param {string} string The string to convert.
  1717. * @returns {Array} Returns the converted array.
  1718. */
  1719. function unicodeToArray(string) {
  1720. return string.match(reUnicode) || [];
  1721. }
  1722. /**
  1723. * Converts `string` to an array.
  1724. *
  1725. * @private
  1726. * @param {string} string The string to convert.
  1727. * @returns {Array} Returns the converted array.
  1728. */
  1729. function stringToArray(string) {
  1730. return hasUnicode(string)
  1731. ? unicodeToArray(string)
  1732. : asciiToArray(string);
  1733. }
  1734. /**
  1735. * Converts `value` to a string. An empty string is returned for `null`
  1736. * and `undefined` values. The sign of `-0` is preserved.
  1737. *
  1738. * @static
  1739. * @memberOf _
  1740. * @since 4.0.0
  1741. * @category Lang
  1742. * @param {*} value The value to convert.
  1743. * @returns {string} Returns the converted string.
  1744. * @example
  1745. *
  1746. * _.toString(null);
  1747. * // => ''
  1748. *
  1749. * _.toString(-0);
  1750. * // => '-0'
  1751. *
  1752. * _.toString([1, 2, 3]);
  1753. * // => '1,2,3'
  1754. */
  1755. function toString(value) {
  1756. return value == null ? '' : baseToString(value);
  1757. }
  1758. /** Used to match leading and trailing whitespace. */
  1759. var reTrim = /^\s+|\s+$/g;
  1760. /**
  1761. * Removes leading and trailing whitespace or specified characters from `string`.
  1762. *
  1763. * @static
  1764. * @memberOf _
  1765. * @since 3.0.0
  1766. * @category String
  1767. * @param {string} [string=''] The string to trim.
  1768. * @param {string} [chars=whitespace] The characters to trim.
  1769. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  1770. * @returns {string} Returns the trimmed string.
  1771. * @example
  1772. *
  1773. * _.trim(' abc ');
  1774. * // => 'abc'
  1775. *
  1776. * _.trim('-_-abc-_-', '_-');
  1777. * // => 'abc'
  1778. *
  1779. * _.map([' foo ', ' bar '], _.trim);
  1780. * // => ['foo', 'bar']
  1781. */
  1782. function trim(string, chars, guard) {
  1783. string = toString(string);
  1784. if (string && (guard || chars === undefined)) {
  1785. return string.replace(reTrim, '');
  1786. }
  1787. if (!string || !(chars = baseToString(chars))) {
  1788. return string;
  1789. }
  1790. var strSymbols = stringToArray(string),
  1791. chrSymbols = stringToArray(chars),
  1792. start = charsStartIndex(strSymbols, chrSymbols),
  1793. end = charsEndIndex(strSymbols, chrSymbols) + 1;
  1794. return castSlice(strSymbols, start, end).join('');
  1795. }
  1796. var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m;
  1797. var FN_ARG_SPLIT = /,/;
  1798. var FN_ARG = /(=.+)?(\s*)$/;
  1799. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  1800. function parseParams(func) {
  1801. func = func.toString().replace(STRIP_COMMENTS, '');
  1802. func = func.match(FN_ARGS)[2].replace(' ', '');
  1803. func = func ? func.split(FN_ARG_SPLIT) : [];
  1804. func = func.map(function (arg){
  1805. return trim(arg.replace(FN_ARG, ''));
  1806. });
  1807. return func;
  1808. }
  1809. /**
  1810. * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent
  1811. * tasks are specified as parameters to the function, after the usual callback
  1812. * parameter, with the parameter names matching the names of the tasks it
  1813. * depends on. This can provide even more readable task graphs which can be
  1814. * easier to maintain.
  1815. *
  1816. * If a final callback is specified, the task results are similarly injected,
  1817. * specified as named parameters after the initial error parameter.
  1818. *
  1819. * The autoInject function is purely syntactic sugar and its semantics are
  1820. * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.
  1821. *
  1822. * @name autoInject
  1823. * @static
  1824. * @memberOf module:ControlFlow
  1825. * @method
  1826. * @see [async.auto]{@link module:ControlFlow.auto}
  1827. * @category Control Flow
  1828. * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of
  1829. * the form 'func([dependencies...], callback). The object's key of a property
  1830. * serves as the name of the task defined by that property, i.e. can be used
  1831. * when specifying requirements for other tasks.
  1832. * * The `callback` parameter is a `callback(err, result)` which must be called
  1833. * when finished, passing an `error` (which can be `null`) and the result of
  1834. * the function's execution. The remaining parameters name other tasks on
  1835. * which the task is dependent, and the results from those tasks are the
  1836. * arguments of those parameters.
  1837. * @param {Function} [callback] - An optional callback which is called when all
  1838. * the tasks have been completed. It receives the `err` argument if any `tasks`
  1839. * pass an error to their callback, and a `results` object with any completed
  1840. * task results, similar to `auto`.
  1841. * @example
  1842. *
  1843. * // The example from `auto` can be rewritten as follows:
  1844. * async.autoInject({
  1845. * get_data: function(callback) {
  1846. * // async code to get some data
  1847. * callback(null, 'data', 'converted to array');
  1848. * },
  1849. * make_folder: function(callback) {
  1850. * // async code to create a directory to store a file in
  1851. * // this is run at the same time as getting the data
  1852. * callback(null, 'folder');
  1853. * },
  1854. * write_file: function(get_data, make_folder, callback) {
  1855. * // once there is some data and the directory exists,
  1856. * // write the data to a file in the directory
  1857. * callback(null, 'filename');
  1858. * },
  1859. * email_link: function(write_file, callback) {
  1860. * // once the file is written let's email a link to it...
  1861. * // write_file contains the filename returned by write_file.
  1862. * callback(null, {'file':write_file, 'email':'user@example.com'});
  1863. * }
  1864. * }, function(err, results) {
  1865. * console.log('err = ', err);
  1866. * console.log('email_link = ', results.email_link);
  1867. * });
  1868. *
  1869. * // If you are using a JS minifier that mangles parameter names, `autoInject`
  1870. * // will not work with plain functions, since the parameter names will be
  1871. * // collapsed to a single letter identifier. To work around this, you can
  1872. * // explicitly specify the names of the parameters your task function needs
  1873. * // in an array, similar to Angular.js dependency injection.
  1874. *
  1875. * // This still has an advantage over plain `auto`, since the results a task
  1876. * // depends on are still spread into arguments.
  1877. * async.autoInject({
  1878. * //...
  1879. * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
  1880. * callback(null, 'filename');
  1881. * }],
  1882. * email_link: ['write_file', function(write_file, callback) {
  1883. * callback(null, {'file':write_file, 'email':'user@example.com'});
  1884. * }]
  1885. * //...
  1886. * }, function(err, results) {
  1887. * console.log('err = ', err);
  1888. * console.log('email_link = ', results.email_link);
  1889. * });
  1890. */
  1891. function autoInject(tasks, callback) {
  1892. var newTasks = {};
  1893. baseForOwn(tasks, function (taskFn, key) {
  1894. var params;
  1895. var fnIsAsync = isAsync(taskFn);
  1896. var hasNoDeps =
  1897. (!fnIsAsync && taskFn.length === 1) ||
  1898. (fnIsAsync && taskFn.length === 0);
  1899. if (isArray(taskFn)) {
  1900. params = taskFn.slice(0, -1);
  1901. taskFn = taskFn[taskFn.length - 1];
  1902. newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
  1903. } else if (hasNoDeps) {
  1904. // no dependencies, use the function as-is
  1905. newTasks[key] = taskFn;
  1906. } else {
  1907. params = parseParams(taskFn);
  1908. if (taskFn.length === 0 && !fnIsAsync && params.length === 0) {
  1909. throw new Error("autoInject task functions require explicit parameters.");
  1910. }
  1911. // remove callback param
  1912. if (!fnIsAsync) params.pop();
  1913. newTasks[key] = params.concat(newTask);
  1914. }
  1915. function newTask(results, taskCb) {
  1916. var newArgs = arrayMap(params, function (name) {
  1917. return results[name];
  1918. });
  1919. newArgs.push(taskCb);
  1920. wrapAsync(taskFn).apply(null, newArgs);
  1921. }
  1922. });
  1923. auto(newTasks, callback);
  1924. }
  1925. // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
  1926. // used for queues. This implementation assumes that the node provided by the user can be modified
  1927. // to adjust the next and last properties. We implement only the minimal functionality
  1928. // for queue support.
  1929. function DLL() {
  1930. this.head = this.tail = null;
  1931. this.length = 0;
  1932. }
  1933. function setInitial(dll, node) {
  1934. dll.length = 1;
  1935. dll.head = dll.tail = node;
  1936. }
  1937. DLL.prototype.removeLink = function(node) {
  1938. if (node.prev) node.prev.next = node.next;
  1939. else this.head = node.next;
  1940. if (node.next) node.next.prev = node.prev;
  1941. else this.tail = node.prev;
  1942. node.prev = node.next = null;
  1943. this.length -= 1;
  1944. return node;
  1945. };
  1946. DLL.prototype.empty = function () {
  1947. while(this.head) this.shift();
  1948. return this;
  1949. };
  1950. DLL.prototype.insertAfter = function(node, newNode) {
  1951. newNode.prev = node;
  1952. newNode.next = node.next;
  1953. if (node.next) node.next.prev = newNode;
  1954. else this.tail = newNode;
  1955. node.next = newNode;
  1956. this.length += 1;
  1957. };
  1958. DLL.prototype.insertBefore = function(node, newNode) {
  1959. newNode.prev = node.prev;
  1960. newNode.next = node;
  1961. if (node.prev) node.prev.next = newNode;
  1962. else this.head = newNode;
  1963. node.prev = newNode;
  1964. this.length += 1;
  1965. };
  1966. DLL.prototype.unshift = function(node) {
  1967. if (this.head) this.insertBefore(this.head, node);
  1968. else setInitial(this, node);
  1969. };
  1970. DLL.prototype.push = function(node) {
  1971. if (this.tail) this.insertAfter(this.tail, node);
  1972. else setInitial(this, node);
  1973. };
  1974. DLL.prototype.shift = function() {
  1975. return this.head && this.removeLink(this.head);
  1976. };
  1977. DLL.prototype.pop = function() {
  1978. return this.tail && this.removeLink(this.tail);
  1979. };
  1980. DLL.prototype.toArray = function () {
  1981. var arr = Array(this.length);
  1982. var curr = this.head;
  1983. for(var idx = 0; idx < this.length; idx++) {
  1984. arr[idx] = curr.data;
  1985. curr = curr.next;
  1986. }
  1987. return arr;
  1988. };
  1989. DLL.prototype.remove = function (testFn) {
  1990. var curr = this.head;
  1991. while(!!curr) {
  1992. var next = curr.next;
  1993. if (testFn(curr)) {
  1994. this.removeLink(curr);
  1995. }
  1996. curr = next;
  1997. }
  1998. return this;
  1999. };
  2000. function queue(worker, concurrency, payload) {
  2001. if (concurrency == null) {
  2002. concurrency = 1;
  2003. }
  2004. else if(concurrency === 0) {
  2005. throw new Error('Concurrency must not be zero');
  2006. }
  2007. var _worker = wrapAsync(worker);
  2008. var numRunning = 0;
  2009. var workersList = [];
  2010. var processingScheduled = false;
  2011. function _insert(data, insertAtFront, callback) {
  2012. if (callback != null && typeof callback !== 'function') {
  2013. throw new Error('task callback must be a function');
  2014. }
  2015. q.started = true;
  2016. if (!isArray(data)) {
  2017. data = [data];
  2018. }
  2019. if (data.length === 0 && q.idle()) {
  2020. // call drain immediately if there are no tasks
  2021. return setImmediate$1(function() {
  2022. q.drain();
  2023. });
  2024. }
  2025. for (var i = 0, l = data.length; i < l; i++) {
  2026. var item = {
  2027. data: data[i],
  2028. callback: callback || noop
  2029. };
  2030. if (insertAtFront) {
  2031. q._tasks.unshift(item);
  2032. } else {
  2033. q._tasks.push(item);
  2034. }
  2035. }
  2036. if (!processingScheduled) {
  2037. processingScheduled = true;
  2038. setImmediate$1(function() {
  2039. processingScheduled = false;
  2040. q.process();
  2041. });
  2042. }
  2043. }
  2044. function _next(tasks) {
  2045. return function(err){
  2046. numRunning -= 1;
  2047. for (var i = 0, l = tasks.length; i < l; i++) {
  2048. var task = tasks[i];
  2049. var index = baseIndexOf(workersList, task, 0);
  2050. if (index === 0) {
  2051. workersList.shift();
  2052. } else if (index > 0) {
  2053. workersList.splice(index, 1);
  2054. }
  2055. task.callback.apply(task, arguments);
  2056. if (err != null) {
  2057. q.error(err, task.data);
  2058. }
  2059. }
  2060. if (numRunning <= (q.concurrency - q.buffer) ) {
  2061. q.unsaturated();
  2062. }
  2063. if (q.idle()) {
  2064. q.drain();
  2065. }
  2066. q.process();
  2067. };
  2068. }
  2069. var isProcessing = false;
  2070. var q = {
  2071. _tasks: new DLL(),
  2072. concurrency: concurrency,
  2073. payload: payload,
  2074. saturated: noop,
  2075. unsaturated:noop,
  2076. buffer: concurrency / 4,
  2077. empty: noop,
  2078. drain: noop,
  2079. error: noop,
  2080. started: false,
  2081. paused: false,
  2082. push: function (data, callback) {
  2083. _insert(data, false, callback);
  2084. },
  2085. kill: function () {
  2086. q.drain = noop;
  2087. q._tasks.empty();
  2088. },
  2089. unshift: function (data, callback) {
  2090. _insert(data, true, callback);
  2091. },
  2092. remove: function (testFn) {
  2093. q._tasks.remove(testFn);
  2094. },
  2095. process: function () {
  2096. // Avoid trying to start too many processing operations. This can occur
  2097. // when callbacks resolve synchronously (#1267).
  2098. if (isProcessing) {
  2099. return;
  2100. }
  2101. isProcessing = true;
  2102. while(!q.paused && numRunning < q.concurrency && q._tasks.length){
  2103. var tasks = [], data = [];
  2104. var l = q._tasks.length;
  2105. if (q.payload) l = Math.min(l, q.payload);
  2106. for (var i = 0; i < l; i++) {
  2107. var node = q._tasks.shift();
  2108. tasks.push(node);
  2109. workersList.push(node);
  2110. data.push(node.data);
  2111. }
  2112. numRunning += 1;
  2113. if (q._tasks.length === 0) {
  2114. q.empty();
  2115. }
  2116. if (numRunning === q.concurrency) {
  2117. q.saturated();
  2118. }
  2119. var cb = onlyOnce(_next(tasks));
  2120. _worker(data, cb);
  2121. }
  2122. isProcessing = false;
  2123. },
  2124. length: function () {
  2125. return q._tasks.length;
  2126. },
  2127. running: function () {
  2128. return numRunning;
  2129. },
  2130. workersList: function () {
  2131. return workersList;
  2132. },
  2133. idle: function() {
  2134. return q._tasks.length + numRunning === 0;
  2135. },
  2136. pause: function () {
  2137. q.paused = true;
  2138. },
  2139. resume: function () {
  2140. if (q.paused === false) { return; }
  2141. q.paused = false;
  2142. setImmediate$1(q.process);
  2143. }
  2144. };
  2145. return q;
  2146. }
  2147. /**
  2148. * A cargo of tasks for the worker function to complete. Cargo inherits all of
  2149. * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}.
  2150. * @typedef {Object} CargoObject
  2151. * @memberOf module:ControlFlow
  2152. * @property {Function} length - A function returning the number of items
  2153. * waiting to be processed. Invoke like `cargo.length()`.
  2154. * @property {number} payload - An `integer` for determining how many tasks
  2155. * should be process per round. This property can be changed after a `cargo` is
  2156. * created to alter the payload on-the-fly.
  2157. * @property {Function} push - Adds `task` to the `queue`. The callback is
  2158. * called once the `worker` has finished processing the task. Instead of a
  2159. * single task, an array of `tasks` can be submitted. The respective callback is
  2160. * used for every task in the list. Invoke like `cargo.push(task, [callback])`.
  2161. * @property {Function} saturated - A callback that is called when the
  2162. * `queue.length()` hits the concurrency and further tasks will be queued.
  2163. * @property {Function} empty - A callback that is called when the last item
  2164. * from the `queue` is given to a `worker`.
  2165. * @property {Function} drain - A callback that is called when the last item
  2166. * from the `queue` has returned from the `worker`.
  2167. * @property {Function} idle - a function returning false if there are items
  2168. * waiting or being processed, or true if not. Invoke like `cargo.idle()`.
  2169. * @property {Function} pause - a function that pauses the processing of tasks
  2170. * until `resume()` is called. Invoke like `cargo.pause()`.
  2171. * @property {Function} resume - a function that resumes the processing of
  2172. * queued tasks when the queue is paused. Invoke like `cargo.resume()`.
  2173. * @property {Function} kill - a function that removes the `drain` callback and
  2174. * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`.
  2175. */
  2176. /**
  2177. * Creates a `cargo` object with the specified payload. Tasks added to the
  2178. * cargo will be processed altogether (up to the `payload` limit). If the
  2179. * `worker` is in progress, the task is queued until it becomes available. Once
  2180. * the `worker` has completed some tasks, each callback of those tasks is
  2181. * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
  2182. * for how `cargo` and `queue` work.
  2183. *
  2184. * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
  2185. * at a time, cargo passes an array of tasks to a single worker, repeating
  2186. * when the worker is finished.
  2187. *
  2188. * @name cargo
  2189. * @static
  2190. * @memberOf module:ControlFlow
  2191. * @method
  2192. * @see [async.queue]{@link module:ControlFlow.queue}
  2193. * @category Control Flow
  2194. * @param {AsyncFunction} worker - An asynchronous function for processing an array
  2195. * of queued tasks. Invoked with `(tasks, callback)`.
  2196. * @param {number} [payload=Infinity] - An optional `integer` for determining
  2197. * how many tasks should be processed per round; if omitted, the default is
  2198. * unlimited.
  2199. * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can
  2200. * attached as certain properties to listen for specific events during the
  2201. * lifecycle of the cargo and inner queue.
  2202. * @example
  2203. *
  2204. * // create a cargo object with payload 2
  2205. * var cargo = async.cargo(function(tasks, callback) {
  2206. * for (var i=0; i<tasks.length; i++) {
  2207. * console.log('hello ' + tasks[i].name);
  2208. * }
  2209. * callback();
  2210. * }, 2);
  2211. *
  2212. * // add some items
  2213. * cargo.push({name: 'foo'}, function(err) {
  2214. * console.log('finished processing foo');
  2215. * });
  2216. * cargo.push({name: 'bar'}, function(err) {
  2217. * console.log('finished processing bar');
  2218. * });
  2219. * cargo.push({name: 'baz'}, function(err) {
  2220. * console.log('finished processing baz');
  2221. * });
  2222. */
  2223. function cargo(worker, payload) {
  2224. return queue(worker, 1, payload);
  2225. }
  2226. /**
  2227. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
  2228. *
  2229. * @name eachOfSeries
  2230. * @static
  2231. * @memberOf module:Collections
  2232. * @method
  2233. * @see [async.eachOf]{@link module:Collections.eachOf}
  2234. * @alias forEachOfSeries
  2235. * @category Collection
  2236. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2237. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  2238. * `coll`.
  2239. * Invoked with (item, key, callback).
  2240. * @param {Function} [callback] - A callback which is called when all `iteratee`
  2241. * functions have finished, or an error occurs. Invoked with (err).
  2242. */
  2243. var eachOfSeries = doLimit(eachOfLimit, 1);
  2244. /**
  2245. * Reduces `coll` into a single value using an async `iteratee` to return each
  2246. * successive step. `memo` is the initial state of the reduction. This function
  2247. * only operates in series.
  2248. *
  2249. * For performance reasons, it may make sense to split a call to this function
  2250. * into a parallel map, and then use the normal `Array.prototype.reduce` on the
  2251. * results. This function is for situations where each step in the reduction
  2252. * needs to be async; if you can get the data before reducing it, then it's
  2253. * probably a good idea to do so.
  2254. *
  2255. * @name reduce
  2256. * @static
  2257. * @memberOf module:Collections
  2258. * @method
  2259. * @alias inject
  2260. * @alias foldl
  2261. * @category Collection
  2262. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2263. * @param {*} memo - The initial state of the reduction.
  2264. * @param {AsyncFunction} iteratee - A function applied to each item in the
  2265. * array to produce the next step in the reduction.
  2266. * The `iteratee` should complete with the next state of the reduction.
  2267. * If the iteratee complete with an error, the reduction is stopped and the
  2268. * main `callback` is immediately called with the error.
  2269. * Invoked with (memo, item, callback).
  2270. * @param {Function} [callback] - A callback which is called after all the
  2271. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  2272. * (err, result).
  2273. * @example
  2274. *
  2275. * async.reduce([1,2,3], 0, function(memo, item, callback) {
  2276. * // pointless async:
  2277. * process.nextTick(function() {
  2278. * callback(null, memo + item)
  2279. * });
  2280. * }, function(err, result) {
  2281. * // result is now equal to the last value of memo, which is 6
  2282. * });
  2283. */
  2284. function reduce(coll, memo, iteratee, callback) {
  2285. callback = once(callback || noop);
  2286. var _iteratee = wrapAsync(iteratee);
  2287. eachOfSeries(coll, function(x, i, callback) {
  2288. _iteratee(memo, x, function(err, v) {
  2289. memo = v;
  2290. callback(err);
  2291. });
  2292. }, function(err) {
  2293. callback(err, memo);
  2294. });
  2295. }
  2296. /**
  2297. * Version of the compose function that is more natural to read. Each function
  2298. * consumes the return value of the previous function. It is the equivalent of
  2299. * [compose]{@link module:ControlFlow.compose} with the arguments reversed.
  2300. *
  2301. * Each function is executed with the `this` binding of the composed function.
  2302. *
  2303. * @name seq
  2304. * @static
  2305. * @memberOf module:ControlFlow
  2306. * @method
  2307. * @see [async.compose]{@link module:ControlFlow.compose}
  2308. * @category Control Flow
  2309. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  2310. * @returns {Function} a function that composes the `functions` in order
  2311. * @example
  2312. *
  2313. * // Requires lodash (or underscore), express3 and dresende's orm2.
  2314. * // Part of an app, that fetches cats of the logged user.
  2315. * // This example uses `seq` function to avoid overnesting and error
  2316. * // handling clutter.
  2317. * app.get('/cats', function(request, response) {
  2318. * var User = request.models.User;
  2319. * async.seq(
  2320. * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
  2321. * function(user, fn) {
  2322. * user.getCats(fn); // 'getCats' has signature (callback(err, data))
  2323. * }
  2324. * )(req.session.user_id, function (err, cats) {
  2325. * if (err) {
  2326. * console.error(err);
  2327. * response.json({ status: 'error', message: err.message });
  2328. * } else {
  2329. * response.json({ status: 'ok', message: 'Cats found', data: cats });
  2330. * }
  2331. * });
  2332. * });
  2333. */
  2334. function seq(/*...functions*/) {
  2335. var _functions = arrayMap(arguments, wrapAsync);
  2336. return function(/*...args*/) {
  2337. var args = slice(arguments);
  2338. var that = this;
  2339. var cb = args[args.length - 1];
  2340. if (typeof cb == 'function') {
  2341. args.pop();
  2342. } else {
  2343. cb = noop;
  2344. }
  2345. reduce(_functions, args, function(newargs, fn, cb) {
  2346. fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) {
  2347. var nextargs = slice(arguments, 1);
  2348. cb(err, nextargs);
  2349. }));
  2350. },
  2351. function(err, results) {
  2352. cb.apply(that, [err].concat(results));
  2353. });
  2354. };
  2355. }
  2356. /**
  2357. * Creates a function which is a composition of the passed asynchronous
  2358. * functions. Each function consumes the return value of the function that
  2359. * follows. Composing functions `f()`, `g()`, and `h()` would produce the result
  2360. * of `f(g(h()))`, only this version uses callbacks to obtain the return values.
  2361. *
  2362. * Each function is executed with the `this` binding of the composed function.
  2363. *
  2364. * @name compose
  2365. * @static
  2366. * @memberOf module:ControlFlow
  2367. * @method
  2368. * @category Control Flow
  2369. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  2370. * @returns {Function} an asynchronous function that is the composed
  2371. * asynchronous `functions`
  2372. * @example
  2373. *
  2374. * function add1(n, callback) {
  2375. * setTimeout(function () {
  2376. * callback(null, n + 1);
  2377. * }, 10);
  2378. * }
  2379. *
  2380. * function mul3(n, callback) {
  2381. * setTimeout(function () {
  2382. * callback(null, n * 3);
  2383. * }, 10);
  2384. * }
  2385. *
  2386. * var add1mul3 = async.compose(mul3, add1);
  2387. * add1mul3(4, function (err, result) {
  2388. * // result now equals 15
  2389. * });
  2390. */
  2391. var compose = function(/*...args*/) {
  2392. return seq.apply(null, slice(arguments).reverse());
  2393. };
  2394. var _concat = Array.prototype.concat;
  2395. /**
  2396. * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.
  2397. *
  2398. * @name concatLimit
  2399. * @static
  2400. * @memberOf module:Collections
  2401. * @method
  2402. * @see [async.concat]{@link module:Collections.concat}
  2403. * @category Collection
  2404. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2405. * @param {number} limit - The maximum number of async operations at a time.
  2406. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  2407. * which should use an array as its result. Invoked with (item, callback).
  2408. * @param {Function} [callback] - A callback which is called after all the
  2409. * `iteratee` functions have finished, or an error occurs. Results is an array
  2410. * containing the concatenated results of the `iteratee` function. Invoked with
  2411. * (err, results).
  2412. */
  2413. var concatLimit = function(coll, limit, iteratee, callback) {
  2414. callback = callback || noop;
  2415. var _iteratee = wrapAsync(iteratee);
  2416. mapLimit(coll, limit, function(val, callback) {
  2417. _iteratee(val, function(err /*, ...args*/) {
  2418. if (err) return callback(err);
  2419. return callback(null, slice(arguments, 1));
  2420. });
  2421. }, function(err, mapResults) {
  2422. var result = [];
  2423. for (var i = 0; i < mapResults.length; i++) {
  2424. if (mapResults[i]) {
  2425. result = _concat.apply(result, mapResults[i]);
  2426. }
  2427. }
  2428. return callback(err, result);
  2429. });
  2430. };
  2431. /**
  2432. * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
  2433. * the concatenated list. The `iteratee`s are called in parallel, and the
  2434. * results are concatenated as they return. There is no guarantee that the
  2435. * results array will be returned in the original order of `coll` passed to the
  2436. * `iteratee` function.
  2437. *
  2438. * @name concat
  2439. * @static
  2440. * @memberOf module:Collections
  2441. * @method
  2442. * @category Collection
  2443. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2444. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  2445. * which should use an array as its result. Invoked with (item, callback).
  2446. * @param {Function} [callback(err)] - A callback which is called after all the
  2447. * `iteratee` functions have finished, or an error occurs. Results is an array
  2448. * containing the concatenated results of the `iteratee` function. Invoked with
  2449. * (err, results).
  2450. * @example
  2451. *
  2452. * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
  2453. * // files is now a list of filenames that exist in the 3 directories
  2454. * });
  2455. */
  2456. var concat = doLimit(concatLimit, Infinity);
  2457. /**
  2458. * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
  2459. *
  2460. * @name concatSeries
  2461. * @static
  2462. * @memberOf module:Collections
  2463. * @method
  2464. * @see [async.concat]{@link module:Collections.concat}
  2465. * @category Collection
  2466. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2467. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.
  2468. * The iteratee should complete with an array an array of results.
  2469. * Invoked with (item, callback).
  2470. * @param {Function} [callback(err)] - A callback which is called after all the
  2471. * `iteratee` functions have finished, or an error occurs. Results is an array
  2472. * containing the concatenated results of the `iteratee` function. Invoked with
  2473. * (err, results).
  2474. */
  2475. var concatSeries = doLimit(concatLimit, 1);
  2476. /**
  2477. * Returns a function that when called, calls-back with the values provided.
  2478. * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
  2479. * [`auto`]{@link module:ControlFlow.auto}.
  2480. *
  2481. * @name constant
  2482. * @static
  2483. * @memberOf module:Utils
  2484. * @method
  2485. * @category Util
  2486. * @param {...*} arguments... - Any number of arguments to automatically invoke
  2487. * callback with.
  2488. * @returns {AsyncFunction} Returns a function that when invoked, automatically
  2489. * invokes the callback with the previous given arguments.
  2490. * @example
  2491. *
  2492. * async.waterfall([
  2493. * async.constant(42),
  2494. * function (value, next) {
  2495. * // value === 42
  2496. * },
  2497. * //...
  2498. * ], callback);
  2499. *
  2500. * async.waterfall([
  2501. * async.constant(filename, "utf8"),
  2502. * fs.readFile,
  2503. * function (fileData, next) {
  2504. * //...
  2505. * }
  2506. * //...
  2507. * ], callback);
  2508. *
  2509. * async.auto({
  2510. * hostname: async.constant("https://server.net/"),
  2511. * port: findFreePort,
  2512. * launchServer: ["hostname", "port", function (options, cb) {
  2513. * startServer(options, cb);
  2514. * }],
  2515. * //...
  2516. * }, callback);
  2517. */
  2518. var constant = function(/*...values*/) {
  2519. var values = slice(arguments);
  2520. var args = [null].concat(values);
  2521. return function (/*...ignoredArgs, callback*/) {
  2522. var callback = arguments[arguments.length - 1];
  2523. return callback.apply(this, args);
  2524. };
  2525. };
  2526. /**
  2527. * This method returns the first argument it receives.
  2528. *
  2529. * @static
  2530. * @since 0.1.0
  2531. * @memberOf _
  2532. * @category Util
  2533. * @param {*} value Any value.
  2534. * @returns {*} Returns `value`.
  2535. * @example
  2536. *
  2537. * var object = { 'a': 1 };
  2538. *
  2539. * console.log(_.identity(object) === object);
  2540. * // => true
  2541. */
  2542. function identity(value) {
  2543. return value;
  2544. }
  2545. function _createTester(check, getResult) {
  2546. return function(eachfn, arr, iteratee, cb) {
  2547. cb = cb || noop;
  2548. var testPassed = false;
  2549. var testResult;
  2550. eachfn(arr, function(value, _, callback) {
  2551. iteratee(value, function(err, result) {
  2552. if (err) {
  2553. callback(err);
  2554. } else if (check(result) && !testResult) {
  2555. testPassed = true;
  2556. testResult = getResult(true, value);
  2557. callback(null, breakLoop);
  2558. } else {
  2559. callback();
  2560. }
  2561. });
  2562. }, function(err) {
  2563. if (err) {
  2564. cb(err);
  2565. } else {
  2566. cb(null, testPassed ? testResult : getResult(false));
  2567. }
  2568. });
  2569. };
  2570. }
  2571. function _findGetResult(v, x) {
  2572. return x;
  2573. }
  2574. /**
  2575. * Returns the first value in `coll` that passes an async truth test. The
  2576. * `iteratee` is applied in parallel, meaning the first iteratee to return
  2577. * `true` will fire the detect `callback` with that result. That means the
  2578. * result might not be the first item in the original `coll` (in terms of order)
  2579. * that passes the test.
  2580. * If order within the original `coll` is important, then look at
  2581. * [`detectSeries`]{@link module:Collections.detectSeries}.
  2582. *
  2583. * @name detect
  2584. * @static
  2585. * @memberOf module:Collections
  2586. * @method
  2587. * @alias find
  2588. * @category Collections
  2589. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2590. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  2591. * The iteratee must complete with a boolean value as its result.
  2592. * Invoked with (item, callback).
  2593. * @param {Function} [callback] - A callback which is called as soon as any
  2594. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  2595. * Result will be the first item in the array that passes the truth test
  2596. * (iteratee) or the value `undefined` if none passed. Invoked with
  2597. * (err, result).
  2598. * @example
  2599. *
  2600. * async.detect(['file1','file2','file3'], function(filePath, callback) {
  2601. * fs.access(filePath, function(err) {
  2602. * callback(null, !err)
  2603. * });
  2604. * }, function(err, result) {
  2605. * // result now equals the first file in the list that exists
  2606. * });
  2607. */
  2608. var detect = doParallel(_createTester(identity, _findGetResult));
  2609. /**
  2610. * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
  2611. * time.
  2612. *
  2613. * @name detectLimit
  2614. * @static
  2615. * @memberOf module:Collections
  2616. * @method
  2617. * @see [async.detect]{@link module:Collections.detect}
  2618. * @alias findLimit
  2619. * @category Collections
  2620. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2621. * @param {number} limit - The maximum number of async operations at a time.
  2622. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  2623. * The iteratee must complete with a boolean value as its result.
  2624. * Invoked with (item, callback).
  2625. * @param {Function} [callback] - A callback which is called as soon as any
  2626. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  2627. * Result will be the first item in the array that passes the truth test
  2628. * (iteratee) or the value `undefined` if none passed. Invoked with
  2629. * (err, result).
  2630. */
  2631. var detectLimit = doParallelLimit(_createTester(identity, _findGetResult));
  2632. /**
  2633. * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
  2634. *
  2635. * @name detectSeries
  2636. * @static
  2637. * @memberOf module:Collections
  2638. * @method
  2639. * @see [async.detect]{@link module:Collections.detect}
  2640. * @alias findSeries
  2641. * @category Collections
  2642. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2643. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  2644. * The iteratee must complete with a boolean value as its result.
  2645. * Invoked with (item, callback).
  2646. * @param {Function} [callback] - A callback which is called as soon as any
  2647. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  2648. * Result will be the first item in the array that passes the truth test
  2649. * (iteratee) or the value `undefined` if none passed. Invoked with
  2650. * (err, result).
  2651. */
  2652. var detectSeries = doLimit(detectLimit, 1);
  2653. function consoleFunc(name) {
  2654. return function (fn/*, ...args*/) {
  2655. var args = slice(arguments, 1);
  2656. args.push(function (err/*, ...args*/) {
  2657. var args = slice(arguments, 1);
  2658. if (typeof console === 'object') {
  2659. if (err) {
  2660. if (console.error) {
  2661. console.error(err);
  2662. }
  2663. } else if (console[name]) {
  2664. arrayEach(args, function (x) {
  2665. console[name](x);
  2666. });
  2667. }
  2668. }
  2669. });
  2670. wrapAsync(fn).apply(null, args);
  2671. };
  2672. }
  2673. /**
  2674. * Logs the result of an [`async` function]{@link AsyncFunction} to the
  2675. * `console` using `console.dir` to display the properties of the resulting object.
  2676. * Only works in Node.js or in browsers that support `console.dir` and
  2677. * `console.error` (such as FF and Chrome).
  2678. * If multiple arguments are returned from the async function,
  2679. * `console.dir` is called on each argument in order.
  2680. *
  2681. * @name dir
  2682. * @static
  2683. * @memberOf module:Utils
  2684. * @method
  2685. * @category Util
  2686. * @param {AsyncFunction} function - The function you want to eventually apply
  2687. * all arguments to.
  2688. * @param {...*} arguments... - Any number of arguments to apply to the function.
  2689. * @example
  2690. *
  2691. * // in a module
  2692. * var hello = function(name, callback) {
  2693. * setTimeout(function() {
  2694. * callback(null, {hello: name});
  2695. * }, 1000);
  2696. * };
  2697. *
  2698. * // in the node repl
  2699. * node> async.dir(hello, 'world');
  2700. * {hello: 'world'}
  2701. */
  2702. var dir = consoleFunc('dir');
  2703. /**
  2704. * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in
  2705. * the order of operations, the arguments `test` and `fn` are switched.
  2706. *
  2707. * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function.
  2708. * @name doDuring
  2709. * @static
  2710. * @memberOf module:ControlFlow
  2711. * @method
  2712. * @see [async.during]{@link module:ControlFlow.during}
  2713. * @category Control Flow
  2714. * @param {AsyncFunction} fn - An async function which is called each time
  2715. * `test` passes. Invoked with (callback).
  2716. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  2717. * execution of `fn`. Invoked with (...args, callback), where `...args` are the
  2718. * non-error args from the previous callback of `fn`.
  2719. * @param {Function} [callback] - A callback which is called after the test
  2720. * function has failed and repeated execution of `fn` has stopped. `callback`
  2721. * will be passed an error if one occurred, otherwise `null`.
  2722. */
  2723. function doDuring(fn, test, callback) {
  2724. callback = onlyOnce(callback || noop);
  2725. var _fn = wrapAsync(fn);
  2726. var _test = wrapAsync(test);
  2727. function next(err/*, ...args*/) {
  2728. if (err) return callback(err);
  2729. var args = slice(arguments, 1);
  2730. args.push(check);
  2731. _test.apply(this, args);
  2732. }
  2733. function check(err, truth) {
  2734. if (err) return callback(err);
  2735. if (!truth) return callback(null);
  2736. _fn(next);
  2737. }
  2738. check(null, true);
  2739. }
  2740. /**
  2741. * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
  2742. * the order of operations, the arguments `test` and `iteratee` are switched.
  2743. *
  2744. * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
  2745. *
  2746. * @name doWhilst
  2747. * @static
  2748. * @memberOf module:ControlFlow
  2749. * @method
  2750. * @see [async.whilst]{@link module:ControlFlow.whilst}
  2751. * @category Control Flow
  2752. * @param {AsyncFunction} iteratee - A function which is called each time `test`
  2753. * passes. Invoked with (callback).
  2754. * @param {Function} test - synchronous truth test to perform after each
  2755. * execution of `iteratee`. Invoked with any non-error callback results of
  2756. * `iteratee`.
  2757. * @param {Function} [callback] - A callback which is called after the test
  2758. * function has failed and repeated execution of `iteratee` has stopped.
  2759. * `callback` will be passed an error and any arguments passed to the final
  2760. * `iteratee`'s callback. Invoked with (err, [results]);
  2761. */
  2762. function doWhilst(iteratee, test, callback) {
  2763. callback = onlyOnce(callback || noop);
  2764. var _iteratee = wrapAsync(iteratee);
  2765. var next = function(err/*, ...args*/) {
  2766. if (err) return callback(err);
  2767. var args = slice(arguments, 1);
  2768. if (test.apply(this, args)) return _iteratee(next);
  2769. callback.apply(null, [null].concat(args));
  2770. };
  2771. _iteratee(next);
  2772. }
  2773. /**
  2774. * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the
  2775. * argument ordering differs from `until`.
  2776. *
  2777. * @name doUntil
  2778. * @static
  2779. * @memberOf module:ControlFlow
  2780. * @method
  2781. * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}
  2782. * @category Control Flow
  2783. * @param {AsyncFunction} iteratee - An async function which is called each time
  2784. * `test` fails. Invoked with (callback).
  2785. * @param {Function} test - synchronous truth test to perform after each
  2786. * execution of `iteratee`. Invoked with any non-error callback results of
  2787. * `iteratee`.
  2788. * @param {Function} [callback] - A callback which is called after the test
  2789. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  2790. * will be passed an error and any arguments passed to the final `iteratee`'s
  2791. * callback. Invoked with (err, [results]);
  2792. */
  2793. function doUntil(iteratee, test, callback) {
  2794. doWhilst(iteratee, function() {
  2795. return !test.apply(this, arguments);
  2796. }, callback);
  2797. }
  2798. /**
  2799. * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that
  2800. * is passed a callback in the form of `function (err, truth)`. If error is
  2801. * passed to `test` or `fn`, the main callback is immediately called with the
  2802. * value of the error.
  2803. *
  2804. * @name during
  2805. * @static
  2806. * @memberOf module:ControlFlow
  2807. * @method
  2808. * @see [async.whilst]{@link module:ControlFlow.whilst}
  2809. * @category Control Flow
  2810. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  2811. * execution of `fn`. Invoked with (callback).
  2812. * @param {AsyncFunction} fn - An async function which is called each time
  2813. * `test` passes. Invoked with (callback).
  2814. * @param {Function} [callback] - A callback which is called after the test
  2815. * function has failed and repeated execution of `fn` has stopped. `callback`
  2816. * will be passed an error, if one occurred, otherwise `null`.
  2817. * @example
  2818. *
  2819. * var count = 0;
  2820. *
  2821. * async.during(
  2822. * function (callback) {
  2823. * return callback(null, count < 5);
  2824. * },
  2825. * function (callback) {
  2826. * count++;
  2827. * setTimeout(callback, 1000);
  2828. * },
  2829. * function (err) {
  2830. * // 5 seconds have passed
  2831. * }
  2832. * );
  2833. */
  2834. function during(test, fn, callback) {
  2835. callback = onlyOnce(callback || noop);
  2836. var _fn = wrapAsync(fn);
  2837. var _test = wrapAsync(test);
  2838. function next(err) {
  2839. if (err) return callback(err);
  2840. _test(check);
  2841. }
  2842. function check(err, truth) {
  2843. if (err) return callback(err);
  2844. if (!truth) return callback(null);
  2845. _fn(next);
  2846. }
  2847. _test(check);
  2848. }
  2849. function _withoutIndex(iteratee) {
  2850. return function (value, index, callback) {
  2851. return iteratee(value, callback);
  2852. };
  2853. }
  2854. /**
  2855. * Applies the function `iteratee` to each item in `coll`, in parallel.
  2856. * The `iteratee` is called with an item from the list, and a callback for when
  2857. * it has finished. If the `iteratee` passes an error to its `callback`, the
  2858. * main `callback` (for the `each` function) is immediately called with the
  2859. * error.
  2860. *
  2861. * Note, that since this function applies `iteratee` to each item in parallel,
  2862. * there is no guarantee that the iteratee functions will complete in order.
  2863. *
  2864. * @name each
  2865. * @static
  2866. * @memberOf module:Collections
  2867. * @method
  2868. * @alias forEach
  2869. * @category Collection
  2870. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2871. * @param {AsyncFunction} iteratee - An async function to apply to
  2872. * each item in `coll`. Invoked with (item, callback).
  2873. * The array index is not passed to the iteratee.
  2874. * If you need the index, use `eachOf`.
  2875. * @param {Function} [callback] - A callback which is called when all
  2876. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  2877. * @example
  2878. *
  2879. * // assuming openFiles is an array of file names and saveFile is a function
  2880. * // to save the modified contents of that file:
  2881. *
  2882. * async.each(openFiles, saveFile, function(err){
  2883. * // if any of the saves produced an error, err would equal that error
  2884. * });
  2885. *
  2886. * // assuming openFiles is an array of file names
  2887. * async.each(openFiles, function(file, callback) {
  2888. *
  2889. * // Perform operation on file here.
  2890. * console.log('Processing file ' + file);
  2891. *
  2892. * if( file.length > 32 ) {
  2893. * console.log('This file name is too long');
  2894. * callback('File name too long');
  2895. * } else {
  2896. * // Do work to process file here
  2897. * console.log('File processed');
  2898. * callback();
  2899. * }
  2900. * }, function(err) {
  2901. * // if any of the file processing produced an error, err would equal that error
  2902. * if( err ) {
  2903. * // One of the iterations produced an error.
  2904. * // All processing will now stop.
  2905. * console.log('A file failed to process');
  2906. * } else {
  2907. * console.log('All files have been processed successfully');
  2908. * }
  2909. * });
  2910. */
  2911. function eachLimit(coll, iteratee, callback) {
  2912. eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  2913. }
  2914. /**
  2915. * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
  2916. *
  2917. * @name eachLimit
  2918. * @static
  2919. * @memberOf module:Collections
  2920. * @method
  2921. * @see [async.each]{@link module:Collections.each}
  2922. * @alias forEachLimit
  2923. * @category Collection
  2924. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2925. * @param {number} limit - The maximum number of async operations at a time.
  2926. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  2927. * `coll`.
  2928. * The array index is not passed to the iteratee.
  2929. * If you need the index, use `eachOfLimit`.
  2930. * Invoked with (item, callback).
  2931. * @param {Function} [callback] - A callback which is called when all
  2932. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  2933. */
  2934. function eachLimit$1(coll, limit, iteratee, callback) {
  2935. _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  2936. }
  2937. /**
  2938. * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
  2939. *
  2940. * @name eachSeries
  2941. * @static
  2942. * @memberOf module:Collections
  2943. * @method
  2944. * @see [async.each]{@link module:Collections.each}
  2945. * @alias forEachSeries
  2946. * @category Collection
  2947. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2948. * @param {AsyncFunction} iteratee - An async function to apply to each
  2949. * item in `coll`.
  2950. * The array index is not passed to the iteratee.
  2951. * If you need the index, use `eachOfSeries`.
  2952. * Invoked with (item, callback).
  2953. * @param {Function} [callback] - A callback which is called when all
  2954. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  2955. */
  2956. var eachSeries = doLimit(eachLimit$1, 1);
  2957. /**
  2958. * Wrap an async function and ensure it calls its callback on a later tick of
  2959. * the event loop. If the function already calls its callback on a next tick,
  2960. * no extra deferral is added. This is useful for preventing stack overflows
  2961. * (`RangeError: Maximum call stack size exceeded`) and generally keeping
  2962. * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
  2963. * contained. ES2017 `async` functions are returned as-is -- they are immune
  2964. * to Zalgo's corrupting influences, as they always resolve on a later tick.
  2965. *
  2966. * @name ensureAsync
  2967. * @static
  2968. * @memberOf module:Utils
  2969. * @method
  2970. * @category Util
  2971. * @param {AsyncFunction} fn - an async function, one that expects a node-style
  2972. * callback as its last argument.
  2973. * @returns {AsyncFunction} Returns a wrapped function with the exact same call
  2974. * signature as the function passed in.
  2975. * @example
  2976. *
  2977. * function sometimesAsync(arg, callback) {
  2978. * if (cache[arg]) {
  2979. * return callback(null, cache[arg]); // this would be synchronous!!
  2980. * } else {
  2981. * doSomeIO(arg, callback); // this IO would be asynchronous
  2982. * }
  2983. * }
  2984. *
  2985. * // this has a risk of stack overflows if many results are cached in a row
  2986. * async.mapSeries(args, sometimesAsync, done);
  2987. *
  2988. * // this will defer sometimesAsync's callback if necessary,
  2989. * // preventing stack overflows
  2990. * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
  2991. */
  2992. function ensureAsync(fn) {
  2993. if (isAsync(fn)) return fn;
  2994. return initialParams(function (args, callback) {
  2995. var sync = true;
  2996. args.push(function () {
  2997. var innerArgs = arguments;
  2998. if (sync) {
  2999. setImmediate$1(function () {
  3000. callback.apply(null, innerArgs);
  3001. });
  3002. } else {
  3003. callback.apply(null, innerArgs);
  3004. }
  3005. });
  3006. fn.apply(this, args);
  3007. sync = false;
  3008. });
  3009. }
  3010. function notId(v) {
  3011. return !v;
  3012. }
  3013. /**
  3014. * Returns `true` if every element in `coll` satisfies an async test. If any
  3015. * iteratee call returns `false`, the main `callback` is immediately called.
  3016. *
  3017. * @name every
  3018. * @static
  3019. * @memberOf module:Collections
  3020. * @method
  3021. * @alias all
  3022. * @category Collection
  3023. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3024. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  3025. * in the collection in parallel.
  3026. * The iteratee must complete with a boolean result value.
  3027. * Invoked with (item, callback).
  3028. * @param {Function} [callback] - A callback which is called after all the
  3029. * `iteratee` functions have finished. Result will be either `true` or `false`
  3030. * depending on the values of the async tests. Invoked with (err, result).
  3031. * @example
  3032. *
  3033. * async.every(['file1','file2','file3'], function(filePath, callback) {
  3034. * fs.access(filePath, function(err) {
  3035. * callback(null, !err)
  3036. * });
  3037. * }, function(err, result) {
  3038. * // if result is true then every file exists
  3039. * });
  3040. */
  3041. var every = doParallel(_createTester(notId, notId));
  3042. /**
  3043. * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
  3044. *
  3045. * @name everyLimit
  3046. * @static
  3047. * @memberOf module:Collections
  3048. * @method
  3049. * @see [async.every]{@link module:Collections.every}
  3050. * @alias allLimit
  3051. * @category Collection
  3052. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3053. * @param {number} limit - The maximum number of async operations at a time.
  3054. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  3055. * in the collection in parallel.
  3056. * The iteratee must complete with a boolean result value.
  3057. * Invoked with (item, callback).
  3058. * @param {Function} [callback] - A callback which is called after all the
  3059. * `iteratee` functions have finished. Result will be either `true` or `false`
  3060. * depending on the values of the async tests. Invoked with (err, result).
  3061. */
  3062. var everyLimit = doParallelLimit(_createTester(notId, notId));
  3063. /**
  3064. * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
  3065. *
  3066. * @name everySeries
  3067. * @static
  3068. * @memberOf module:Collections
  3069. * @method
  3070. * @see [async.every]{@link module:Collections.every}
  3071. * @alias allSeries
  3072. * @category Collection
  3073. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3074. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  3075. * in the collection in series.
  3076. * The iteratee must complete with a boolean result value.
  3077. * Invoked with (item, callback).
  3078. * @param {Function} [callback] - A callback which is called after all the
  3079. * `iteratee` functions have finished. Result will be either `true` or `false`
  3080. * depending on the values of the async tests. Invoked with (err, result).
  3081. */
  3082. var everySeries = doLimit(everyLimit, 1);
  3083. /**
  3084. * The base implementation of `_.property` without support for deep paths.
  3085. *
  3086. * @private
  3087. * @param {string} key The key of the property to get.
  3088. * @returns {Function} Returns the new accessor function.
  3089. */
  3090. function baseProperty(key) {
  3091. return function(object) {
  3092. return object == null ? undefined : object[key];
  3093. };
  3094. }
  3095. function filterArray(eachfn, arr, iteratee, callback) {
  3096. var truthValues = new Array(arr.length);
  3097. eachfn(arr, function (x, index, callback) {
  3098. iteratee(x, function (err, v) {
  3099. truthValues[index] = !!v;
  3100. callback(err);
  3101. });
  3102. }, function (err) {
  3103. if (err) return callback(err);
  3104. var results = [];
  3105. for (var i = 0; i < arr.length; i++) {
  3106. if (truthValues[i]) results.push(arr[i]);
  3107. }
  3108. callback(null, results);
  3109. });
  3110. }
  3111. function filterGeneric(eachfn, coll, iteratee, callback) {
  3112. var results = [];
  3113. eachfn(coll, function (x, index, callback) {
  3114. iteratee(x, function (err, v) {
  3115. if (err) {
  3116. callback(err);
  3117. } else {
  3118. if (v) {
  3119. results.push({index: index, value: x});
  3120. }
  3121. callback();
  3122. }
  3123. });
  3124. }, function (err) {
  3125. if (err) {
  3126. callback(err);
  3127. } else {
  3128. callback(null, arrayMap(results.sort(function (a, b) {
  3129. return a.index - b.index;
  3130. }), baseProperty('value')));
  3131. }
  3132. });
  3133. }
  3134. function _filter(eachfn, coll, iteratee, callback) {
  3135. var filter = isArrayLike(coll) ? filterArray : filterGeneric;
  3136. filter(eachfn, coll, wrapAsync(iteratee), callback || noop);
  3137. }
  3138. /**
  3139. * Returns a new array of all the values in `coll` which pass an async truth
  3140. * test. This operation is performed in parallel, but the results array will be
  3141. * in the same order as the original.
  3142. *
  3143. * @name filter
  3144. * @static
  3145. * @memberOf module:Collections
  3146. * @method
  3147. * @alias select
  3148. * @category Collection
  3149. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3150. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  3151. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  3152. * with a boolean argument once it has completed. Invoked with (item, callback).
  3153. * @param {Function} [callback] - A callback which is called after all the
  3154. * `iteratee` functions have finished. Invoked with (err, results).
  3155. * @example
  3156. *
  3157. * async.filter(['file1','file2','file3'], function(filePath, callback) {
  3158. * fs.access(filePath, function(err) {
  3159. * callback(null, !err)
  3160. * });
  3161. * }, function(err, results) {
  3162. * // results now equals an array of the existing files
  3163. * });
  3164. */
  3165. var filter = doParallel(_filter);
  3166. /**
  3167. * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
  3168. * time.
  3169. *
  3170. * @name filterLimit
  3171. * @static
  3172. * @memberOf module:Collections
  3173. * @method
  3174. * @see [async.filter]{@link module:Collections.filter}
  3175. * @alias selectLimit
  3176. * @category Collection
  3177. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3178. * @param {number} limit - The maximum number of async operations at a time.
  3179. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  3180. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  3181. * with a boolean argument once it has completed. Invoked with (item, callback).
  3182. * @param {Function} [callback] - A callback which is called after all the
  3183. * `iteratee` functions have finished. Invoked with (err, results).
  3184. */
  3185. var filterLimit = doParallelLimit(_filter);
  3186. /**
  3187. * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
  3188. *
  3189. * @name filterSeries
  3190. * @static
  3191. * @memberOf module:Collections
  3192. * @method
  3193. * @see [async.filter]{@link module:Collections.filter}
  3194. * @alias selectSeries
  3195. * @category Collection
  3196. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3197. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  3198. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  3199. * with a boolean argument once it has completed. Invoked with (item, callback).
  3200. * @param {Function} [callback] - A callback which is called after all the
  3201. * `iteratee` functions have finished. Invoked with (err, results)
  3202. */
  3203. var filterSeries = doLimit(filterLimit, 1);
  3204. /**
  3205. * Calls the asynchronous function `fn` with a callback parameter that allows it
  3206. * to call itself again, in series, indefinitely.
  3207. * If an error is passed to the callback then `errback` is called with the
  3208. * error, and execution stops, otherwise it will never be called.
  3209. *
  3210. * @name forever
  3211. * @static
  3212. * @memberOf module:ControlFlow
  3213. * @method
  3214. * @category Control Flow
  3215. * @param {AsyncFunction} fn - an async function to call repeatedly.
  3216. * Invoked with (next).
  3217. * @param {Function} [errback] - when `fn` passes an error to it's callback,
  3218. * this function will be called, and execution stops. Invoked with (err).
  3219. * @example
  3220. *
  3221. * async.forever(
  3222. * function(next) {
  3223. * // next is suitable for passing to things that need a callback(err [, whatever]);
  3224. * // it will result in this function being called again.
  3225. * },
  3226. * function(err) {
  3227. * // if next is called with a value in its first parameter, it will appear
  3228. * // in here as 'err', and execution will stop.
  3229. * }
  3230. * );
  3231. */
  3232. function forever(fn, errback) {
  3233. var done = onlyOnce(errback || noop);
  3234. var task = wrapAsync(ensureAsync(fn));
  3235. function next(err) {
  3236. if (err) return done(err);
  3237. task(next);
  3238. }
  3239. next();
  3240. }
  3241. /**
  3242. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.
  3243. *
  3244. * @name groupByLimit
  3245. * @static
  3246. * @memberOf module:Collections
  3247. * @method
  3248. * @see [async.groupBy]{@link module:Collections.groupBy}
  3249. * @category Collection
  3250. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3251. * @param {number} limit - The maximum number of async operations at a time.
  3252. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  3253. * `coll`.
  3254. * The iteratee should complete with a `key` to group the value under.
  3255. * Invoked with (value, callback).
  3256. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3257. * functions have finished, or an error occurs. Result is an `Object` whoses
  3258. * properties are arrays of values which returned the corresponding key.
  3259. */
  3260. var groupByLimit = function(coll, limit, iteratee, callback) {
  3261. callback = callback || noop;
  3262. var _iteratee = wrapAsync(iteratee);
  3263. mapLimit(coll, limit, function(val, callback) {
  3264. _iteratee(val, function(err, key) {
  3265. if (err) return callback(err);
  3266. return callback(null, {key: key, val: val});
  3267. });
  3268. }, function(err, mapResults) {
  3269. var result = {};
  3270. // from MDN, handle object having an `hasOwnProperty` prop
  3271. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3272. for (var i = 0; i < mapResults.length; i++) {
  3273. if (mapResults[i]) {
  3274. var key = mapResults[i].key;
  3275. var val = mapResults[i].val;
  3276. if (hasOwnProperty.call(result, key)) {
  3277. result[key].push(val);
  3278. } else {
  3279. result[key] = [val];
  3280. }
  3281. }
  3282. }
  3283. return callback(err, result);
  3284. });
  3285. };
  3286. /**
  3287. * Returns a new object, where each value corresponds to an array of items, from
  3288. * `coll`, that returned the corresponding key. That is, the keys of the object
  3289. * correspond to the values passed to the `iteratee` callback.
  3290. *
  3291. * Note: Since this function applies the `iteratee` to each item in parallel,
  3292. * there is no guarantee that the `iteratee` functions will complete in order.
  3293. * However, the values for each key in the `result` will be in the same order as
  3294. * the original `coll`. For Objects, the values will roughly be in the order of
  3295. * the original Objects' keys (but this can vary across JavaScript engines).
  3296. *
  3297. * @name groupBy
  3298. * @static
  3299. * @memberOf module:Collections
  3300. * @method
  3301. * @category Collection
  3302. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3303. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  3304. * `coll`.
  3305. * The iteratee should complete with a `key` to group the value under.
  3306. * Invoked with (value, callback).
  3307. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3308. * functions have finished, or an error occurs. Result is an `Object` whoses
  3309. * properties are arrays of values which returned the corresponding key.
  3310. * @example
  3311. *
  3312. * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) {
  3313. * db.findById(userId, function(err, user) {
  3314. * if (err) return callback(err);
  3315. * return callback(null, user.age);
  3316. * });
  3317. * }, function(err, result) {
  3318. * // result is object containing the userIds grouped by age
  3319. * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']};
  3320. * });
  3321. */
  3322. var groupBy = doLimit(groupByLimit, Infinity);
  3323. /**
  3324. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.
  3325. *
  3326. * @name groupBySeries
  3327. * @static
  3328. * @memberOf module:Collections
  3329. * @method
  3330. * @see [async.groupBy]{@link module:Collections.groupBy}
  3331. * @category Collection
  3332. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3333. * @param {number} limit - The maximum number of async operations at a time.
  3334. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  3335. * `coll`.
  3336. * The iteratee should complete with a `key` to group the value under.
  3337. * Invoked with (value, callback).
  3338. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3339. * functions have finished, or an error occurs. Result is an `Object` whoses
  3340. * properties are arrays of values which returned the corresponding key.
  3341. */
  3342. var groupBySeries = doLimit(groupByLimit, 1);
  3343. /**
  3344. * Logs the result of an `async` function to the `console`. Only works in
  3345. * Node.js or in browsers that support `console.log` and `console.error` (such
  3346. * as FF and Chrome). If multiple arguments are returned from the async
  3347. * function, `console.log` is called on each argument in order.
  3348. *
  3349. * @name log
  3350. * @static
  3351. * @memberOf module:Utils
  3352. * @method
  3353. * @category Util
  3354. * @param {AsyncFunction} function - The function you want to eventually apply
  3355. * all arguments to.
  3356. * @param {...*} arguments... - Any number of arguments to apply to the function.
  3357. * @example
  3358. *
  3359. * // in a module
  3360. * var hello = function(name, callback) {
  3361. * setTimeout(function() {
  3362. * callback(null, 'hello ' + name);
  3363. * }, 1000);
  3364. * };
  3365. *
  3366. * // in the node repl
  3367. * node> async.log(hello, 'world');
  3368. * 'hello world'
  3369. */
  3370. var log = consoleFunc('log');
  3371. /**
  3372. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
  3373. * time.
  3374. *
  3375. * @name mapValuesLimit
  3376. * @static
  3377. * @memberOf module:Collections
  3378. * @method
  3379. * @see [async.mapValues]{@link module:Collections.mapValues}
  3380. * @category Collection
  3381. * @param {Object} obj - A collection to iterate over.
  3382. * @param {number} limit - The maximum number of async operations at a time.
  3383. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  3384. * in `coll`.
  3385. * The iteratee should complete with the transformed value as its result.
  3386. * Invoked with (value, key, callback).
  3387. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3388. * functions have finished, or an error occurs. `result` is a new object consisting
  3389. * of each key from `obj`, with each transformed value on the right-hand side.
  3390. * Invoked with (err, result).
  3391. */
  3392. function mapValuesLimit(obj, limit, iteratee, callback) {
  3393. callback = once(callback || noop);
  3394. var newObj = {};
  3395. var _iteratee = wrapAsync(iteratee);
  3396. eachOfLimit(obj, limit, function(val, key, next) {
  3397. _iteratee(val, key, function (err, result) {
  3398. if (err) return next(err);
  3399. newObj[key] = result;
  3400. next();
  3401. });
  3402. }, function (err) {
  3403. callback(err, newObj);
  3404. });
  3405. }
  3406. /**
  3407. * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.
  3408. *
  3409. * Produces a new Object by mapping each value of `obj` through the `iteratee`
  3410. * function. The `iteratee` is called each `value` and `key` from `obj` and a
  3411. * callback for when it has finished processing. Each of these callbacks takes
  3412. * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`
  3413. * passes an error to its callback, the main `callback` (for the `mapValues`
  3414. * function) is immediately called with the error.
  3415. *
  3416. * Note, the order of the keys in the result is not guaranteed. The keys will
  3417. * be roughly in the order they complete, (but this is very engine-specific)
  3418. *
  3419. * @name mapValues
  3420. * @static
  3421. * @memberOf module:Collections
  3422. * @method
  3423. * @category Collection
  3424. * @param {Object} obj - A collection to iterate over.
  3425. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  3426. * in `coll`.
  3427. * The iteratee should complete with the transformed value as its result.
  3428. * Invoked with (value, key, callback).
  3429. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3430. * functions have finished, or an error occurs. `result` is a new object consisting
  3431. * of each key from `obj`, with each transformed value on the right-hand side.
  3432. * Invoked with (err, result).
  3433. * @example
  3434. *
  3435. * async.mapValues({
  3436. * f1: 'file1',
  3437. * f2: 'file2',
  3438. * f3: 'file3'
  3439. * }, function (file, key, callback) {
  3440. * fs.stat(file, callback);
  3441. * }, function(err, result) {
  3442. * // result is now a map of stats for each file, e.g.
  3443. * // {
  3444. * // f1: [stats for file1],
  3445. * // f2: [stats for file2],
  3446. * // f3: [stats for file3]
  3447. * // }
  3448. * });
  3449. */
  3450. var mapValues = doLimit(mapValuesLimit, Infinity);
  3451. /**
  3452. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.
  3453. *
  3454. * @name mapValuesSeries
  3455. * @static
  3456. * @memberOf module:Collections
  3457. * @method
  3458. * @see [async.mapValues]{@link module:Collections.mapValues}
  3459. * @category Collection
  3460. * @param {Object} obj - A collection to iterate over.
  3461. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  3462. * in `coll`.
  3463. * The iteratee should complete with the transformed value as its result.
  3464. * Invoked with (value, key, callback).
  3465. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3466. * functions have finished, or an error occurs. `result` is a new object consisting
  3467. * of each key from `obj`, with each transformed value on the right-hand side.
  3468. * Invoked with (err, result).
  3469. */
  3470. var mapValuesSeries = doLimit(mapValuesLimit, 1);
  3471. function has(obj, key) {
  3472. return key in obj;
  3473. }
  3474. /**
  3475. * Caches the results of an async function. When creating a hash to store
  3476. * function results against, the callback is omitted from the hash and an
  3477. * optional hash function can be used.
  3478. *
  3479. * If no hash function is specified, the first argument is used as a hash key,
  3480. * which may work reasonably if it is a string or a data type that converts to a
  3481. * distinct string. Note that objects and arrays will not behave reasonably.
  3482. * Neither will cases where the other arguments are significant. In such cases,
  3483. * specify your own hash function.
  3484. *
  3485. * The cache of results is exposed as the `memo` property of the function
  3486. * returned by `memoize`.
  3487. *
  3488. * @name memoize
  3489. * @static
  3490. * @memberOf module:Utils
  3491. * @method
  3492. * @category Util
  3493. * @param {AsyncFunction} fn - The async function to proxy and cache results from.
  3494. * @param {Function} hasher - An optional function for generating a custom hash
  3495. * for storing results. It has all the arguments applied to it apart from the
  3496. * callback, and must be synchronous.
  3497. * @returns {AsyncFunction} a memoized version of `fn`
  3498. * @example
  3499. *
  3500. * var slow_fn = function(name, callback) {
  3501. * // do something
  3502. * callback(null, result);
  3503. * };
  3504. * var fn = async.memoize(slow_fn);
  3505. *
  3506. * // fn can now be used as if it were slow_fn
  3507. * fn('some name', function() {
  3508. * // callback
  3509. * });
  3510. */
  3511. function memoize(fn, hasher) {
  3512. var memo = Object.create(null);
  3513. var queues = Object.create(null);
  3514. hasher = hasher || identity;
  3515. var _fn = wrapAsync(fn);
  3516. var memoized = initialParams(function memoized(args, callback) {
  3517. var key = hasher.apply(null, args);
  3518. if (has(memo, key)) {
  3519. setImmediate$1(function() {
  3520. callback.apply(null, memo[key]);
  3521. });
  3522. } else if (has(queues, key)) {
  3523. queues[key].push(callback);
  3524. } else {
  3525. queues[key] = [callback];
  3526. _fn.apply(null, args.concat(function(/*args*/) {
  3527. var args = slice(arguments);
  3528. memo[key] = args;
  3529. var q = queues[key];
  3530. delete queues[key];
  3531. for (var i = 0, l = q.length; i < l; i++) {
  3532. q[i].apply(null, args);
  3533. }
  3534. }));
  3535. }
  3536. });
  3537. memoized.memo = memo;
  3538. memoized.unmemoized = fn;
  3539. return memoized;
  3540. }
  3541. /**
  3542. * Calls `callback` on a later loop around the event loop. In Node.js this just
  3543. * calls `process.nextTick`. In the browser it will use `setImmediate` if
  3544. * available, otherwise `setTimeout(callback, 0)`, which means other higher
  3545. * priority events may precede the execution of `callback`.
  3546. *
  3547. * This is used internally for browser-compatibility purposes.
  3548. *
  3549. * @name nextTick
  3550. * @static
  3551. * @memberOf module:Utils
  3552. * @method
  3553. * @see [async.setImmediate]{@link module:Utils.setImmediate}
  3554. * @category Util
  3555. * @param {Function} callback - The function to call on a later loop around
  3556. * the event loop. Invoked with (args...).
  3557. * @param {...*} args... - any number of additional arguments to pass to the
  3558. * callback on the next tick.
  3559. * @example
  3560. *
  3561. * var call_order = [];
  3562. * async.nextTick(function() {
  3563. * call_order.push('two');
  3564. * // call_order now equals ['one','two']
  3565. * });
  3566. * call_order.push('one');
  3567. *
  3568. * async.setImmediate(function (a, b, c) {
  3569. * // a, b, and c equal 1, 2, and 3
  3570. * }, 1, 2, 3);
  3571. */
  3572. var _defer$1;
  3573. if (hasNextTick) {
  3574. _defer$1 = process.nextTick;
  3575. } else if (hasSetImmediate) {
  3576. _defer$1 = setImmediate;
  3577. } else {
  3578. _defer$1 = fallback;
  3579. }
  3580. var nextTick = wrap(_defer$1);
  3581. function _parallel(eachfn, tasks, callback) {
  3582. callback = callback || noop;
  3583. var results = isArrayLike(tasks) ? [] : {};
  3584. eachfn(tasks, function (task, key, callback) {
  3585. wrapAsync(task)(function (err, result) {
  3586. if (arguments.length > 2) {
  3587. result = slice(arguments, 1);
  3588. }
  3589. results[key] = result;
  3590. callback(err);
  3591. });
  3592. }, function (err) {
  3593. callback(err, results);
  3594. });
  3595. }
  3596. /**
  3597. * Run the `tasks` collection of functions in parallel, without waiting until
  3598. * the previous function has completed. If any of the functions pass an error to
  3599. * its callback, the main `callback` is immediately called with the value of the
  3600. * error. Once the `tasks` have completed, the results are passed to the final
  3601. * `callback` as an array.
  3602. *
  3603. * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about
  3604. * parallel execution of code. If your tasks do not use any timers or perform
  3605. * any I/O, they will actually be executed in series. Any synchronous setup
  3606. * sections for each task will happen one after the other. JavaScript remains
  3607. * single-threaded.
  3608. *
  3609. * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the
  3610. * execution of other tasks when a task fails.
  3611. *
  3612. * It is also possible to use an object instead of an array. Each property will
  3613. * be run as a function and the results will be passed to the final `callback`
  3614. * as an object instead of an array. This can be a more readable way of handling
  3615. * results from {@link async.parallel}.
  3616. *
  3617. * @name parallel
  3618. * @static
  3619. * @memberOf module:ControlFlow
  3620. * @method
  3621. * @category Control Flow
  3622. * @param {Array|Iterable|Object} tasks - A collection of
  3623. * [async functions]{@link AsyncFunction} to run.
  3624. * Each async function can complete with any number of optional `result` values.
  3625. * @param {Function} [callback] - An optional callback to run once all the
  3626. * functions have completed successfully. This function gets a results array
  3627. * (or object) containing all the result arguments passed to the task callbacks.
  3628. * Invoked with (err, results).
  3629. *
  3630. * @example
  3631. * async.parallel([
  3632. * function(callback) {
  3633. * setTimeout(function() {
  3634. * callback(null, 'one');
  3635. * }, 200);
  3636. * },
  3637. * function(callback) {
  3638. * setTimeout(function() {
  3639. * callback(null, 'two');
  3640. * }, 100);
  3641. * }
  3642. * ],
  3643. * // optional callback
  3644. * function(err, results) {
  3645. * // the results array will equal ['one','two'] even though
  3646. * // the second function had a shorter timeout.
  3647. * });
  3648. *
  3649. * // an example using an object instead of an array
  3650. * async.parallel({
  3651. * one: function(callback) {
  3652. * setTimeout(function() {
  3653. * callback(null, 1);
  3654. * }, 200);
  3655. * },
  3656. * two: function(callback) {
  3657. * setTimeout(function() {
  3658. * callback(null, 2);
  3659. * }, 100);
  3660. * }
  3661. * }, function(err, results) {
  3662. * // results is now equals to: {one: 1, two: 2}
  3663. * });
  3664. */
  3665. function parallelLimit(tasks, callback) {
  3666. _parallel(eachOf, tasks, callback);
  3667. }
  3668. /**
  3669. * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a
  3670. * time.
  3671. *
  3672. * @name parallelLimit
  3673. * @static
  3674. * @memberOf module:ControlFlow
  3675. * @method
  3676. * @see [async.parallel]{@link module:ControlFlow.parallel}
  3677. * @category Control Flow
  3678. * @param {Array|Iterable|Object} tasks - A collection of
  3679. * [async functions]{@link AsyncFunction} to run.
  3680. * Each async function can complete with any number of optional `result` values.
  3681. * @param {number} limit - The maximum number of async operations at a time.
  3682. * @param {Function} [callback] - An optional callback to run once all the
  3683. * functions have completed successfully. This function gets a results array
  3684. * (or object) containing all the result arguments passed to the task callbacks.
  3685. * Invoked with (err, results).
  3686. */
  3687. function parallelLimit$1(tasks, limit, callback) {
  3688. _parallel(_eachOfLimit(limit), tasks, callback);
  3689. }
  3690. /**
  3691. * A queue of tasks for the worker function to complete.
  3692. * @typedef {Object} QueueObject
  3693. * @memberOf module:ControlFlow
  3694. * @property {Function} length - a function returning the number of items
  3695. * waiting to be processed. Invoke with `queue.length()`.
  3696. * @property {boolean} started - a boolean indicating whether or not any
  3697. * items have been pushed and processed by the queue.
  3698. * @property {Function} running - a function returning the number of items
  3699. * currently being processed. Invoke with `queue.running()`.
  3700. * @property {Function} workersList - a function returning the array of items
  3701. * currently being processed. Invoke with `queue.workersList()`.
  3702. * @property {Function} idle - a function returning false if there are items
  3703. * waiting or being processed, or true if not. Invoke with `queue.idle()`.
  3704. * @property {number} concurrency - an integer for determining how many `worker`
  3705. * functions should be run in parallel. This property can be changed after a
  3706. * `queue` is created to alter the concurrency on-the-fly.
  3707. * @property {Function} push - add a new task to the `queue`. Calls `callback`
  3708. * once the `worker` has finished processing the task. Instead of a single task,
  3709. * a `tasks` array can be submitted. The respective callback is used for every
  3710. * task in the list. Invoke with `queue.push(task, [callback])`,
  3711. * @property {Function} unshift - add a new task to the front of the `queue`.
  3712. * Invoke with `queue.unshift(task, [callback])`.
  3713. * @property {Function} remove - remove items from the queue that match a test
  3714. * function. The test function will be passed an object with a `data` property,
  3715. * and a `priority` property, if this is a
  3716. * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
  3717. * Invoked with `queue.remove(testFn)`, where `testFn` is of the form
  3718. * `function ({data, priority}) {}` and returns a Boolean.
  3719. * @property {Function} saturated - a callback that is called when the number of
  3720. * running workers hits the `concurrency` limit, and further tasks will be
  3721. * queued.
  3722. * @property {Function} unsaturated - a callback that is called when the number
  3723. * of running workers is less than the `concurrency` & `buffer` limits, and
  3724. * further tasks will not be queued.
  3725. * @property {number} buffer - A minimum threshold buffer in order to say that
  3726. * the `queue` is `unsaturated`.
  3727. * @property {Function} empty - a callback that is called when the last item
  3728. * from the `queue` is given to a `worker`.
  3729. * @property {Function} drain - a callback that is called when the last item
  3730. * from the `queue` has returned from the `worker`.
  3731. * @property {Function} error - a callback that is called when a task errors.
  3732. * Has the signature `function(error, task)`.
  3733. * @property {boolean} paused - a boolean for determining whether the queue is
  3734. * in a paused state.
  3735. * @property {Function} pause - a function that pauses the processing of tasks
  3736. * until `resume()` is called. Invoke with `queue.pause()`.
  3737. * @property {Function} resume - a function that resumes the processing of
  3738. * queued tasks when the queue is paused. Invoke with `queue.resume()`.
  3739. * @property {Function} kill - a function that removes the `drain` callback and
  3740. * empties remaining tasks from the queue forcing it to go idle. No more tasks
  3741. * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
  3742. */
  3743. /**
  3744. * Creates a `queue` object with the specified `concurrency`. Tasks added to the
  3745. * `queue` are processed in parallel (up to the `concurrency` limit). If all
  3746. * `worker`s are in progress, the task is queued until one becomes available.
  3747. * Once a `worker` completes a `task`, that `task`'s callback is called.
  3748. *
  3749. * @name queue
  3750. * @static
  3751. * @memberOf module:ControlFlow
  3752. * @method
  3753. * @category Control Flow
  3754. * @param {AsyncFunction} worker - An async function for processing a queued task.
  3755. * If you want to handle errors from an individual task, pass a callback to
  3756. * `q.push()`. Invoked with (task, callback).
  3757. * @param {number} [concurrency=1] - An `integer` for determining how many
  3758. * `worker` functions should be run in parallel. If omitted, the concurrency
  3759. * defaults to `1`. If the concurrency is `0`, an error is thrown.
  3760. * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can
  3761. * attached as certain properties to listen for specific events during the
  3762. * lifecycle of the queue.
  3763. * @example
  3764. *
  3765. * // create a queue object with concurrency 2
  3766. * var q = async.queue(function(task, callback) {
  3767. * console.log('hello ' + task.name);
  3768. * callback();
  3769. * }, 2);
  3770. *
  3771. * // assign a callback
  3772. * q.drain = function() {
  3773. * console.log('all items have been processed');
  3774. * };
  3775. *
  3776. * // add some items to the queue
  3777. * q.push({name: 'foo'}, function(err) {
  3778. * console.log('finished processing foo');
  3779. * });
  3780. * q.push({name: 'bar'}, function (err) {
  3781. * console.log('finished processing bar');
  3782. * });
  3783. *
  3784. * // add some items to the queue (batch-wise)
  3785. * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
  3786. * console.log('finished processing item');
  3787. * });
  3788. *
  3789. * // add some items to the front of the queue
  3790. * q.unshift({name: 'bar'}, function (err) {
  3791. * console.log('finished processing bar');
  3792. * });
  3793. */
  3794. var queue$1 = function (worker, concurrency) {
  3795. var _worker = wrapAsync(worker);
  3796. return queue(function (items, cb) {
  3797. _worker(items[0], cb);
  3798. }, concurrency, 1);
  3799. };
  3800. /**
  3801. * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and
  3802. * completed in ascending priority order.
  3803. *
  3804. * @name priorityQueue
  3805. * @static
  3806. * @memberOf module:ControlFlow
  3807. * @method
  3808. * @see [async.queue]{@link module:ControlFlow.queue}
  3809. * @category Control Flow
  3810. * @param {AsyncFunction} worker - An async function for processing a queued task.
  3811. * If you want to handle errors from an individual task, pass a callback to
  3812. * `q.push()`.
  3813. * Invoked with (task, callback).
  3814. * @param {number} concurrency - An `integer` for determining how many `worker`
  3815. * functions should be run in parallel. If omitted, the concurrency defaults to
  3816. * `1`. If the concurrency is `0`, an error is thrown.
  3817. * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two
  3818. * differences between `queue` and `priorityQueue` objects:
  3819. * * `push(task, priority, [callback])` - `priority` should be a number. If an
  3820. * array of `tasks` is given, all tasks will be assigned the same priority.
  3821. * * The `unshift` method was removed.
  3822. */
  3823. var priorityQueue = function(worker, concurrency) {
  3824. // Start with a normal queue
  3825. var q = queue$1(worker, concurrency);
  3826. // Override push to accept second parameter representing priority
  3827. q.push = function(data, priority, callback) {
  3828. if (callback == null) callback = noop;
  3829. if (typeof callback !== 'function') {
  3830. throw new Error('task callback must be a function');
  3831. }
  3832. q.started = true;
  3833. if (!isArray(data)) {
  3834. data = [data];
  3835. }
  3836. if (data.length === 0) {
  3837. // call drain immediately if there are no tasks
  3838. return setImmediate$1(function() {
  3839. q.drain();
  3840. });
  3841. }
  3842. priority = priority || 0;
  3843. var nextNode = q._tasks.head;
  3844. while (nextNode && priority >= nextNode.priority) {
  3845. nextNode = nextNode.next;
  3846. }
  3847. for (var i = 0, l = data.length; i < l; i++) {
  3848. var item = {
  3849. data: data[i],
  3850. priority: priority,
  3851. callback: callback
  3852. };
  3853. if (nextNode) {
  3854. q._tasks.insertBefore(nextNode, item);
  3855. } else {
  3856. q._tasks.push(item);
  3857. }
  3858. }
  3859. setImmediate$1(q.process);
  3860. };
  3861. // Remove unshift function
  3862. delete q.unshift;
  3863. return q;
  3864. };
  3865. /**
  3866. * Runs the `tasks` array of functions in parallel, without waiting until the
  3867. * previous function has completed. Once any of the `tasks` complete or pass an
  3868. * error to its callback, the main `callback` is immediately called. It's
  3869. * equivalent to `Promise.race()`.
  3870. *
  3871. * @name race
  3872. * @static
  3873. * @memberOf module:ControlFlow
  3874. * @method
  3875. * @category Control Flow
  3876. * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
  3877. * to run. Each function can complete with an optional `result` value.
  3878. * @param {Function} callback - A callback to run once any of the functions have
  3879. * completed. This function gets an error or result from the first function that
  3880. * completed. Invoked with (err, result).
  3881. * @returns undefined
  3882. * @example
  3883. *
  3884. * async.race([
  3885. * function(callback) {
  3886. * setTimeout(function() {
  3887. * callback(null, 'one');
  3888. * }, 200);
  3889. * },
  3890. * function(callback) {
  3891. * setTimeout(function() {
  3892. * callback(null, 'two');
  3893. * }, 100);
  3894. * }
  3895. * ],
  3896. * // main callback
  3897. * function(err, result) {
  3898. * // the result will be equal to 'two' as it finishes earlier
  3899. * });
  3900. */
  3901. function race(tasks, callback) {
  3902. callback = once(callback || noop);
  3903. if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
  3904. if (!tasks.length) return callback();
  3905. for (var i = 0, l = tasks.length; i < l; i++) {
  3906. wrapAsync(tasks[i])(callback);
  3907. }
  3908. }
  3909. /**
  3910. * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
  3911. *
  3912. * @name reduceRight
  3913. * @static
  3914. * @memberOf module:Collections
  3915. * @method
  3916. * @see [async.reduce]{@link module:Collections.reduce}
  3917. * @alias foldr
  3918. * @category Collection
  3919. * @param {Array} array - A collection to iterate over.
  3920. * @param {*} memo - The initial state of the reduction.
  3921. * @param {AsyncFunction} iteratee - A function applied to each item in the
  3922. * array to produce the next step in the reduction.
  3923. * The `iteratee` should complete with the next state of the reduction.
  3924. * If the iteratee complete with an error, the reduction is stopped and the
  3925. * main `callback` is immediately called with the error.
  3926. * Invoked with (memo, item, callback).
  3927. * @param {Function} [callback] - A callback which is called after all the
  3928. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  3929. * (err, result).
  3930. */
  3931. function reduceRight (array, memo, iteratee, callback) {
  3932. var reversed = slice(array).reverse();
  3933. reduce(reversed, memo, iteratee, callback);
  3934. }
  3935. /**
  3936. * Wraps the async function in another function that always completes with a
  3937. * result object, even when it errors.
  3938. *
  3939. * The result object has either the property `error` or `value`.
  3940. *
  3941. * @name reflect
  3942. * @static
  3943. * @memberOf module:Utils
  3944. * @method
  3945. * @category Util
  3946. * @param {AsyncFunction} fn - The async function you want to wrap
  3947. * @returns {Function} - A function that always passes null to it's callback as
  3948. * the error. The second argument to the callback will be an `object` with
  3949. * either an `error` or a `value` property.
  3950. * @example
  3951. *
  3952. * async.parallel([
  3953. * async.reflect(function(callback) {
  3954. * // do some stuff ...
  3955. * callback(null, 'one');
  3956. * }),
  3957. * async.reflect(function(callback) {
  3958. * // do some more stuff but error ...
  3959. * callback('bad stuff happened');
  3960. * }),
  3961. * async.reflect(function(callback) {
  3962. * // do some more stuff ...
  3963. * callback(null, 'two');
  3964. * })
  3965. * ],
  3966. * // optional callback
  3967. * function(err, results) {
  3968. * // values
  3969. * // results[0].value = 'one'
  3970. * // results[1].error = 'bad stuff happened'
  3971. * // results[2].value = 'two'
  3972. * });
  3973. */
  3974. function reflect(fn) {
  3975. var _fn = wrapAsync(fn);
  3976. return initialParams(function reflectOn(args, reflectCallback) {
  3977. args.push(function callback(error, cbArg) {
  3978. if (error) {
  3979. reflectCallback(null, { error: error });
  3980. } else {
  3981. var value;
  3982. if (arguments.length <= 2) {
  3983. value = cbArg;
  3984. } else {
  3985. value = slice(arguments, 1);
  3986. }
  3987. reflectCallback(null, { value: value });
  3988. }
  3989. });
  3990. return _fn.apply(this, args);
  3991. });
  3992. }
  3993. /**
  3994. * A helper function that wraps an array or an object of functions with `reflect`.
  3995. *
  3996. * @name reflectAll
  3997. * @static
  3998. * @memberOf module:Utils
  3999. * @method
  4000. * @see [async.reflect]{@link module:Utils.reflect}
  4001. * @category Util
  4002. * @param {Array|Object|Iterable} tasks - The collection of
  4003. * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.
  4004. * @returns {Array} Returns an array of async functions, each wrapped in
  4005. * `async.reflect`
  4006. * @example
  4007. *
  4008. * let tasks = [
  4009. * function(callback) {
  4010. * setTimeout(function() {
  4011. * callback(null, 'one');
  4012. * }, 200);
  4013. * },
  4014. * function(callback) {
  4015. * // do some more stuff but error ...
  4016. * callback(new Error('bad stuff happened'));
  4017. * },
  4018. * function(callback) {
  4019. * setTimeout(function() {
  4020. * callback(null, 'two');
  4021. * }, 100);
  4022. * }
  4023. * ];
  4024. *
  4025. * async.parallel(async.reflectAll(tasks),
  4026. * // optional callback
  4027. * function(err, results) {
  4028. * // values
  4029. * // results[0].value = 'one'
  4030. * // results[1].error = Error('bad stuff happened')
  4031. * // results[2].value = 'two'
  4032. * });
  4033. *
  4034. * // an example using an object instead of an array
  4035. * let tasks = {
  4036. * one: function(callback) {
  4037. * setTimeout(function() {
  4038. * callback(null, 'one');
  4039. * }, 200);
  4040. * },
  4041. * two: function(callback) {
  4042. * callback('two');
  4043. * },
  4044. * three: function(callback) {
  4045. * setTimeout(function() {
  4046. * callback(null, 'three');
  4047. * }, 100);
  4048. * }
  4049. * };
  4050. *
  4051. * async.parallel(async.reflectAll(tasks),
  4052. * // optional callback
  4053. * function(err, results) {
  4054. * // values
  4055. * // results.one.value = 'one'
  4056. * // results.two.error = 'two'
  4057. * // results.three.value = 'three'
  4058. * });
  4059. */
  4060. function reflectAll(tasks) {
  4061. var results;
  4062. if (isArray(tasks)) {
  4063. results = arrayMap(tasks, reflect);
  4064. } else {
  4065. results = {};
  4066. baseForOwn(tasks, function(task, key) {
  4067. results[key] = reflect.call(this, task);
  4068. });
  4069. }
  4070. return results;
  4071. }
  4072. function reject$1(eachfn, arr, iteratee, callback) {
  4073. _filter(eachfn, arr, function(value, cb) {
  4074. iteratee(value, function(err, v) {
  4075. cb(err, !v);
  4076. });
  4077. }, callback);
  4078. }
  4079. /**
  4080. * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
  4081. *
  4082. * @name reject
  4083. * @static
  4084. * @memberOf module:Collections
  4085. * @method
  4086. * @see [async.filter]{@link module:Collections.filter}
  4087. * @category Collection
  4088. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4089. * @param {Function} iteratee - An async truth test to apply to each item in
  4090. * `coll`.
  4091. * The should complete with a boolean value as its `result`.
  4092. * Invoked with (item, callback).
  4093. * @param {Function} [callback] - A callback which is called after all the
  4094. * `iteratee` functions have finished. Invoked with (err, results).
  4095. * @example
  4096. *
  4097. * async.reject(['file1','file2','file3'], function(filePath, callback) {
  4098. * fs.access(filePath, function(err) {
  4099. * callback(null, !err)
  4100. * });
  4101. * }, function(err, results) {
  4102. * // results now equals an array of missing files
  4103. * createFiles(results);
  4104. * });
  4105. */
  4106. var reject = doParallel(reject$1);
  4107. /**
  4108. * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
  4109. * time.
  4110. *
  4111. * @name rejectLimit
  4112. * @static
  4113. * @memberOf module:Collections
  4114. * @method
  4115. * @see [async.reject]{@link module:Collections.reject}
  4116. * @category Collection
  4117. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4118. * @param {number} limit - The maximum number of async operations at a time.
  4119. * @param {Function} iteratee - An async truth test to apply to each item in
  4120. * `coll`.
  4121. * The should complete with a boolean value as its `result`.
  4122. * Invoked with (item, callback).
  4123. * @param {Function} [callback] - A callback which is called after all the
  4124. * `iteratee` functions have finished. Invoked with (err, results).
  4125. */
  4126. var rejectLimit = doParallelLimit(reject$1);
  4127. /**
  4128. * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
  4129. *
  4130. * @name rejectSeries
  4131. * @static
  4132. * @memberOf module:Collections
  4133. * @method
  4134. * @see [async.reject]{@link module:Collections.reject}
  4135. * @category Collection
  4136. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4137. * @param {Function} iteratee - An async truth test to apply to each item in
  4138. * `coll`.
  4139. * The should complete with a boolean value as its `result`.
  4140. * Invoked with (item, callback).
  4141. * @param {Function} [callback] - A callback which is called after all the
  4142. * `iteratee` functions have finished. Invoked with (err, results).
  4143. */
  4144. var rejectSeries = doLimit(rejectLimit, 1);
  4145. /**
  4146. * Creates a function that returns `value`.
  4147. *
  4148. * @static
  4149. * @memberOf _
  4150. * @since 2.4.0
  4151. * @category Util
  4152. * @param {*} value The value to return from the new function.
  4153. * @returns {Function} Returns the new constant function.
  4154. * @example
  4155. *
  4156. * var objects = _.times(2, _.constant({ 'a': 1 }));
  4157. *
  4158. * console.log(objects);
  4159. * // => [{ 'a': 1 }, { 'a': 1 }]
  4160. *
  4161. * console.log(objects[0] === objects[1]);
  4162. * // => true
  4163. */
  4164. function constant$1(value) {
  4165. return function() {
  4166. return value;
  4167. };
  4168. }
  4169. /**
  4170. * Attempts to get a successful response from `task` no more than `times` times
  4171. * before returning an error. If the task is successful, the `callback` will be
  4172. * passed the result of the successful task. If all attempts fail, the callback
  4173. * will be passed the error and result (if any) of the final attempt.
  4174. *
  4175. * @name retry
  4176. * @static
  4177. * @memberOf module:ControlFlow
  4178. * @method
  4179. * @category Control Flow
  4180. * @see [async.retryable]{@link module:ControlFlow.retryable}
  4181. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
  4182. * object with `times` and `interval` or a number.
  4183. * * `times` - The number of attempts to make before giving up. The default
  4184. * is `5`.
  4185. * * `interval` - The time to wait between retries, in milliseconds. The
  4186. * default is `0`. The interval may also be specified as a function of the
  4187. * retry count (see example).
  4188. * * `errorFilter` - An optional synchronous function that is invoked on
  4189. * erroneous result. If it returns `true` the retry attempts will continue;
  4190. * if the function returns `false` the retry flow is aborted with the current
  4191. * attempt's error and result being returned to the final callback.
  4192. * Invoked with (err).
  4193. * * If `opts` is a number, the number specifies the number of times to retry,
  4194. * with the default interval of `0`.
  4195. * @param {AsyncFunction} task - An async function to retry.
  4196. * Invoked with (callback).
  4197. * @param {Function} [callback] - An optional callback which is called when the
  4198. * task has succeeded, or after the final failed attempt. It receives the `err`
  4199. * and `result` arguments of the last attempt at completing the `task`. Invoked
  4200. * with (err, results).
  4201. *
  4202. * @example
  4203. *
  4204. * // The `retry` function can be used as a stand-alone control flow by passing
  4205. * // a callback, as shown below:
  4206. *
  4207. * // try calling apiMethod 3 times
  4208. * async.retry(3, apiMethod, function(err, result) {
  4209. * // do something with the result
  4210. * });
  4211. *
  4212. * // try calling apiMethod 3 times, waiting 200 ms between each retry
  4213. * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
  4214. * // do something with the result
  4215. * });
  4216. *
  4217. * // try calling apiMethod 10 times with exponential backoff
  4218. * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
  4219. * async.retry({
  4220. * times: 10,
  4221. * interval: function(retryCount) {
  4222. * return 50 * Math.pow(2, retryCount);
  4223. * }
  4224. * }, apiMethod, function(err, result) {
  4225. * // do something with the result
  4226. * });
  4227. *
  4228. * // try calling apiMethod the default 5 times no delay between each retry
  4229. * async.retry(apiMethod, function(err, result) {
  4230. * // do something with the result
  4231. * });
  4232. *
  4233. * // try calling apiMethod only when error condition satisfies, all other
  4234. * // errors will abort the retry control flow and return to final callback
  4235. * async.retry({
  4236. * errorFilter: function(err) {
  4237. * return err.message === 'Temporary error'; // only retry on a specific error
  4238. * }
  4239. * }, apiMethod, function(err, result) {
  4240. * // do something with the result
  4241. * });
  4242. *
  4243. * // to retry individual methods that are not as reliable within other
  4244. * // control flow functions, use the `retryable` wrapper:
  4245. * async.auto({
  4246. * users: api.getUsers.bind(api),
  4247. * payments: async.retryable(3, api.getPayments.bind(api))
  4248. * }, function(err, results) {
  4249. * // do something with the results
  4250. * });
  4251. *
  4252. */
  4253. function retry(opts, task, callback) {
  4254. var DEFAULT_TIMES = 5;
  4255. var DEFAULT_INTERVAL = 0;
  4256. var options = {
  4257. times: DEFAULT_TIMES,
  4258. intervalFunc: constant$1(DEFAULT_INTERVAL)
  4259. };
  4260. function parseTimes(acc, t) {
  4261. if (typeof t === 'object') {
  4262. acc.times = +t.times || DEFAULT_TIMES;
  4263. acc.intervalFunc = typeof t.interval === 'function' ?
  4264. t.interval :
  4265. constant$1(+t.interval || DEFAULT_INTERVAL);
  4266. acc.errorFilter = t.errorFilter;
  4267. } else if (typeof t === 'number' || typeof t === 'string') {
  4268. acc.times = +t || DEFAULT_TIMES;
  4269. } else {
  4270. throw new Error("Invalid arguments for async.retry");
  4271. }
  4272. }
  4273. if (arguments.length < 3 && typeof opts === 'function') {
  4274. callback = task || noop;
  4275. task = opts;
  4276. } else {
  4277. parseTimes(options, opts);
  4278. callback = callback || noop;
  4279. }
  4280. if (typeof task !== 'function') {
  4281. throw new Error("Invalid arguments for async.retry");
  4282. }
  4283. var _task = wrapAsync(task);
  4284. var attempt = 1;
  4285. function retryAttempt() {
  4286. _task(function(err) {
  4287. if (err && attempt++ < options.times &&
  4288. (typeof options.errorFilter != 'function' ||
  4289. options.errorFilter(err))) {
  4290. setTimeout(retryAttempt, options.intervalFunc(attempt));
  4291. } else {
  4292. callback.apply(null, arguments);
  4293. }
  4294. });
  4295. }
  4296. retryAttempt();
  4297. }
  4298. /**
  4299. * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method
  4300. * wraps a task and makes it retryable, rather than immediately calling it
  4301. * with retries.
  4302. *
  4303. * @name retryable
  4304. * @static
  4305. * @memberOf module:ControlFlow
  4306. * @method
  4307. * @see [async.retry]{@link module:ControlFlow.retry}
  4308. * @category Control Flow
  4309. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
  4310. * options, exactly the same as from `retry`
  4311. * @param {AsyncFunction} task - the asynchronous function to wrap.
  4312. * This function will be passed any arguments passed to the returned wrapper.
  4313. * Invoked with (...args, callback).
  4314. * @returns {AsyncFunction} The wrapped function, which when invoked, will
  4315. * retry on an error, based on the parameters specified in `opts`.
  4316. * This function will accept the same parameters as `task`.
  4317. * @example
  4318. *
  4319. * async.auto({
  4320. * dep1: async.retryable(3, getFromFlakyService),
  4321. * process: ["dep1", async.retryable(3, function (results, cb) {
  4322. * maybeProcessData(results.dep1, cb);
  4323. * })]
  4324. * }, callback);
  4325. */
  4326. var retryable = function (opts, task) {
  4327. if (!task) {
  4328. task = opts;
  4329. opts = null;
  4330. }
  4331. var _task = wrapAsync(task);
  4332. return initialParams(function (args, callback) {
  4333. function taskFn(cb) {
  4334. _task.apply(null, args.concat(cb));
  4335. }
  4336. if (opts) retry(opts, taskFn, callback);
  4337. else retry(taskFn, callback);
  4338. });
  4339. };
  4340. /**
  4341. * Run the functions in the `tasks` collection in series, each one running once
  4342. * the previous function has completed. If any functions in the series pass an
  4343. * error to its callback, no more functions are run, and `callback` is
  4344. * immediately called with the value of the error. Otherwise, `callback`
  4345. * receives an array of results when `tasks` have completed.
  4346. *
  4347. * It is also possible to use an object instead of an array. Each property will
  4348. * be run as a function, and the results will be passed to the final `callback`
  4349. * as an object instead of an array. This can be a more readable way of handling
  4350. * results from {@link async.series}.
  4351. *
  4352. * **Note** that while many implementations preserve the order of object
  4353. * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
  4354. * explicitly states that
  4355. *
  4356. * > The mechanics and order of enumerating the properties is not specified.
  4357. *
  4358. * So if you rely on the order in which your series of functions are executed,
  4359. * and want this to work on all platforms, consider using an array.
  4360. *
  4361. * @name series
  4362. * @static
  4363. * @memberOf module:ControlFlow
  4364. * @method
  4365. * @category Control Flow
  4366. * @param {Array|Iterable|Object} tasks - A collection containing
  4367. * [async functions]{@link AsyncFunction} to run in series.
  4368. * Each function can complete with any number of optional `result` values.
  4369. * @param {Function} [callback] - An optional callback to run once all the
  4370. * functions have completed. This function gets a results array (or object)
  4371. * containing all the result arguments passed to the `task` callbacks. Invoked
  4372. * with (err, result).
  4373. * @example
  4374. * async.series([
  4375. * function(callback) {
  4376. * // do some stuff ...
  4377. * callback(null, 'one');
  4378. * },
  4379. * function(callback) {
  4380. * // do some more stuff ...
  4381. * callback(null, 'two');
  4382. * }
  4383. * ],
  4384. * // optional callback
  4385. * function(err, results) {
  4386. * // results is now equal to ['one', 'two']
  4387. * });
  4388. *
  4389. * async.series({
  4390. * one: function(callback) {
  4391. * setTimeout(function() {
  4392. * callback(null, 1);
  4393. * }, 200);
  4394. * },
  4395. * two: function(callback){
  4396. * setTimeout(function() {
  4397. * callback(null, 2);
  4398. * }, 100);
  4399. * }
  4400. * }, function(err, results) {
  4401. * // results is now equal to: {one: 1, two: 2}
  4402. * });
  4403. */
  4404. function series(tasks, callback) {
  4405. _parallel(eachOfSeries, tasks, callback);
  4406. }
  4407. /**
  4408. * Returns `true` if at least one element in the `coll` satisfies an async test.
  4409. * If any iteratee call returns `true`, the main `callback` is immediately
  4410. * called.
  4411. *
  4412. * @name some
  4413. * @static
  4414. * @memberOf module:Collections
  4415. * @method
  4416. * @alias any
  4417. * @category Collection
  4418. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4419. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  4420. * in the collections in parallel.
  4421. * The iteratee should complete with a boolean `result` value.
  4422. * Invoked with (item, callback).
  4423. * @param {Function} [callback] - A callback which is called as soon as any
  4424. * iteratee returns `true`, or after all the iteratee functions have finished.
  4425. * Result will be either `true` or `false` depending on the values of the async
  4426. * tests. Invoked with (err, result).
  4427. * @example
  4428. *
  4429. * async.some(['file1','file2','file3'], function(filePath, callback) {
  4430. * fs.access(filePath, function(err) {
  4431. * callback(null, !err)
  4432. * });
  4433. * }, function(err, result) {
  4434. * // if result is true then at least one of the files exists
  4435. * });
  4436. */
  4437. var some = doParallel(_createTester(Boolean, identity));
  4438. /**
  4439. * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
  4440. *
  4441. * @name someLimit
  4442. * @static
  4443. * @memberOf module:Collections
  4444. * @method
  4445. * @see [async.some]{@link module:Collections.some}
  4446. * @alias anyLimit
  4447. * @category Collection
  4448. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4449. * @param {number} limit - The maximum number of async operations at a time.
  4450. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  4451. * in the collections in parallel.
  4452. * The iteratee should complete with a boolean `result` value.
  4453. * Invoked with (item, callback).
  4454. * @param {Function} [callback] - A callback which is called as soon as any
  4455. * iteratee returns `true`, or after all the iteratee functions have finished.
  4456. * Result will be either `true` or `false` depending on the values of the async
  4457. * tests. Invoked with (err, result).
  4458. */
  4459. var someLimit = doParallelLimit(_createTester(Boolean, identity));
  4460. /**
  4461. * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
  4462. *
  4463. * @name someSeries
  4464. * @static
  4465. * @memberOf module:Collections
  4466. * @method
  4467. * @see [async.some]{@link module:Collections.some}
  4468. * @alias anySeries
  4469. * @category Collection
  4470. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4471. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  4472. * in the collections in series.
  4473. * The iteratee should complete with a boolean `result` value.
  4474. * Invoked with (item, callback).
  4475. * @param {Function} [callback] - A callback which is called as soon as any
  4476. * iteratee returns `true`, or after all the iteratee functions have finished.
  4477. * Result will be either `true` or `false` depending on the values of the async
  4478. * tests. Invoked with (err, result).
  4479. */
  4480. var someSeries = doLimit(someLimit, 1);
  4481. /**
  4482. * Sorts a list by the results of running each `coll` value through an async
  4483. * `iteratee`.
  4484. *
  4485. * @name sortBy
  4486. * @static
  4487. * @memberOf module:Collections
  4488. * @method
  4489. * @category Collection
  4490. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4491. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  4492. * `coll`.
  4493. * The iteratee should complete with a value to use as the sort criteria as
  4494. * its `result`.
  4495. * Invoked with (item, callback).
  4496. * @param {Function} callback - A callback which is called after all the
  4497. * `iteratee` functions have finished, or an error occurs. Results is the items
  4498. * from the original `coll` sorted by the values returned by the `iteratee`
  4499. * calls. Invoked with (err, results).
  4500. * @example
  4501. *
  4502. * async.sortBy(['file1','file2','file3'], function(file, callback) {
  4503. * fs.stat(file, function(err, stats) {
  4504. * callback(err, stats.mtime);
  4505. * });
  4506. * }, function(err, results) {
  4507. * // results is now the original array of files sorted by
  4508. * // modified date
  4509. * });
  4510. *
  4511. * // By modifying the callback parameter the
  4512. * // sorting order can be influenced:
  4513. *
  4514. * // ascending order
  4515. * async.sortBy([1,9,3,5], function(x, callback) {
  4516. * callback(null, x);
  4517. * }, function(err,result) {
  4518. * // result callback
  4519. * });
  4520. *
  4521. * // descending order
  4522. * async.sortBy([1,9,3,5], function(x, callback) {
  4523. * callback(null, x*-1); //<- x*-1 instead of x, turns the order around
  4524. * }, function(err,result) {
  4525. * // result callback
  4526. * });
  4527. */
  4528. function sortBy (coll, iteratee, callback) {
  4529. var _iteratee = wrapAsync(iteratee);
  4530. map(coll, function (x, callback) {
  4531. _iteratee(x, function (err, criteria) {
  4532. if (err) return callback(err);
  4533. callback(null, {value: x, criteria: criteria});
  4534. });
  4535. }, function (err, results) {
  4536. if (err) return callback(err);
  4537. callback(null, arrayMap(results.sort(comparator), baseProperty('value')));
  4538. });
  4539. function comparator(left, right) {
  4540. var a = left.criteria, b = right.criteria;
  4541. return a < b ? -1 : a > b ? 1 : 0;
  4542. }
  4543. }
  4544. /**
  4545. * Sets a time limit on an asynchronous function. If the function does not call
  4546. * its callback within the specified milliseconds, it will be called with a
  4547. * timeout error. The code property for the error object will be `'ETIMEDOUT'`.
  4548. *
  4549. * @name timeout
  4550. * @static
  4551. * @memberOf module:Utils
  4552. * @method
  4553. * @category Util
  4554. * @param {AsyncFunction} asyncFn - The async function to limit in time.
  4555. * @param {number} milliseconds - The specified time limit.
  4556. * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
  4557. * to timeout Error for more information..
  4558. * @returns {AsyncFunction} Returns a wrapped function that can be used with any
  4559. * of the control flow functions.
  4560. * Invoke this function with the same parameters as you would `asyncFunc`.
  4561. * @example
  4562. *
  4563. * function myFunction(foo, callback) {
  4564. * doAsyncTask(foo, function(err, data) {
  4565. * // handle errors
  4566. * if (err) return callback(err);
  4567. *
  4568. * // do some stuff ...
  4569. *
  4570. * // return processed data
  4571. * return callback(null, data);
  4572. * });
  4573. * }
  4574. *
  4575. * var wrapped = async.timeout(myFunction, 1000);
  4576. *
  4577. * // call `wrapped` as you would `myFunction`
  4578. * wrapped({ bar: 'bar' }, function(err, data) {
  4579. * // if `myFunction` takes < 1000 ms to execute, `err`
  4580. * // and `data` will have their expected values
  4581. *
  4582. * // else `err` will be an Error with the code 'ETIMEDOUT'
  4583. * });
  4584. */
  4585. function timeout(asyncFn, milliseconds, info) {
  4586. var fn = wrapAsync(asyncFn);
  4587. return initialParams(function (args, callback) {
  4588. var timedOut = false;
  4589. var timer;
  4590. function timeoutCallback() {
  4591. var name = asyncFn.name || 'anonymous';
  4592. var error = new Error('Callback function "' + name + '" timed out.');
  4593. error.code = 'ETIMEDOUT';
  4594. if (info) {
  4595. error.info = info;
  4596. }
  4597. timedOut = true;
  4598. callback(error);
  4599. }
  4600. args.push(function () {
  4601. if (!timedOut) {
  4602. callback.apply(null, arguments);
  4603. clearTimeout(timer);
  4604. }
  4605. });
  4606. // setup timer and call original function
  4607. timer = setTimeout(timeoutCallback, milliseconds);
  4608. fn.apply(null, args);
  4609. });
  4610. }
  4611. /* Built-in method references for those with the same name as other `lodash` methods. */
  4612. var nativeCeil = Math.ceil;
  4613. var nativeMax = Math.max;
  4614. /**
  4615. * The base implementation of `_.range` and `_.rangeRight` which doesn't
  4616. * coerce arguments.
  4617. *
  4618. * @private
  4619. * @param {number} start The start of the range.
  4620. * @param {number} end The end of the range.
  4621. * @param {number} step The value to increment or decrement by.
  4622. * @param {boolean} [fromRight] Specify iterating from right to left.
  4623. * @returns {Array} Returns the range of numbers.
  4624. */
  4625. function baseRange(start, end, step, fromRight) {
  4626. var index = -1,
  4627. length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
  4628. result = Array(length);
  4629. while (length--) {
  4630. result[fromRight ? length : ++index] = start;
  4631. start += step;
  4632. }
  4633. return result;
  4634. }
  4635. /**
  4636. * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a
  4637. * time.
  4638. *
  4639. * @name timesLimit
  4640. * @static
  4641. * @memberOf module:ControlFlow
  4642. * @method
  4643. * @see [async.times]{@link module:ControlFlow.times}
  4644. * @category Control Flow
  4645. * @param {number} count - The number of times to run the function.
  4646. * @param {number} limit - The maximum number of async operations at a time.
  4647. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  4648. * Invoked with the iteration index and a callback: (n, next).
  4649. * @param {Function} callback - see [async.map]{@link module:Collections.map}.
  4650. */
  4651. function timeLimit(count, limit, iteratee, callback) {
  4652. var _iteratee = wrapAsync(iteratee);
  4653. mapLimit(baseRange(0, count, 1), limit, _iteratee, callback);
  4654. }
  4655. /**
  4656. * Calls the `iteratee` function `n` times, and accumulates results in the same
  4657. * manner you would use with [map]{@link module:Collections.map}.
  4658. *
  4659. * @name times
  4660. * @static
  4661. * @memberOf module:ControlFlow
  4662. * @method
  4663. * @see [async.map]{@link module:Collections.map}
  4664. * @category Control Flow
  4665. * @param {number} n - The number of times to run the function.
  4666. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  4667. * Invoked with the iteration index and a callback: (n, next).
  4668. * @param {Function} callback - see {@link module:Collections.map}.
  4669. * @example
  4670. *
  4671. * // Pretend this is some complicated async factory
  4672. * var createUser = function(id, callback) {
  4673. * callback(null, {
  4674. * id: 'user' + id
  4675. * });
  4676. * };
  4677. *
  4678. * // generate 5 users
  4679. * async.times(5, function(n, next) {
  4680. * createUser(n, function(err, user) {
  4681. * next(err, user);
  4682. * });
  4683. * }, function(err, users) {
  4684. * // we should now have 5 users
  4685. * });
  4686. */
  4687. var times = doLimit(timeLimit, Infinity);
  4688. /**
  4689. * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.
  4690. *
  4691. * @name timesSeries
  4692. * @static
  4693. * @memberOf module:ControlFlow
  4694. * @method
  4695. * @see [async.times]{@link module:ControlFlow.times}
  4696. * @category Control Flow
  4697. * @param {number} n - The number of times to run the function.
  4698. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  4699. * Invoked with the iteration index and a callback: (n, next).
  4700. * @param {Function} callback - see {@link module:Collections.map}.
  4701. */
  4702. var timesSeries = doLimit(timeLimit, 1);
  4703. /**
  4704. * A relative of `reduce`. Takes an Object or Array, and iterates over each
  4705. * element in series, each step potentially mutating an `accumulator` value.
  4706. * The type of the accumulator defaults to the type of collection passed in.
  4707. *
  4708. * @name transform
  4709. * @static
  4710. * @memberOf module:Collections
  4711. * @method
  4712. * @category Collection
  4713. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4714. * @param {*} [accumulator] - The initial state of the transform. If omitted,
  4715. * it will default to an empty Object or Array, depending on the type of `coll`
  4716. * @param {AsyncFunction} iteratee - A function applied to each item in the
  4717. * collection that potentially modifies the accumulator.
  4718. * Invoked with (accumulator, item, key, callback).
  4719. * @param {Function} [callback] - A callback which is called after all the
  4720. * `iteratee` functions have finished. Result is the transformed accumulator.
  4721. * Invoked with (err, result).
  4722. * @example
  4723. *
  4724. * async.transform([1,2,3], function(acc, item, index, callback) {
  4725. * // pointless async:
  4726. * process.nextTick(function() {
  4727. * acc.push(item * 2)
  4728. * callback(null)
  4729. * });
  4730. * }, function(err, result) {
  4731. * // result is now equal to [2, 4, 6]
  4732. * });
  4733. *
  4734. * @example
  4735. *
  4736. * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
  4737. * setImmediate(function () {
  4738. * obj[key] = val * 2;
  4739. * callback();
  4740. * })
  4741. * }, function (err, result) {
  4742. * // result is equal to {a: 2, b: 4, c: 6}
  4743. * })
  4744. */
  4745. function transform (coll, accumulator, iteratee, callback) {
  4746. if (arguments.length <= 3) {
  4747. callback = iteratee;
  4748. iteratee = accumulator;
  4749. accumulator = isArray(coll) ? [] : {};
  4750. }
  4751. callback = once(callback || noop);
  4752. var _iteratee = wrapAsync(iteratee);
  4753. eachOf(coll, function(v, k, cb) {
  4754. _iteratee(accumulator, v, k, cb);
  4755. }, function(err) {
  4756. callback(err, accumulator);
  4757. });
  4758. }
  4759. /**
  4760. * It runs each task in series but stops whenever any of the functions were
  4761. * successful. If one of the tasks were successful, the `callback` will be
  4762. * passed the result of the successful task. If all tasks fail, the callback
  4763. * will be passed the error and result (if any) of the final attempt.
  4764. *
  4765. * @name tryEach
  4766. * @static
  4767. * @memberOf module:ControlFlow
  4768. * @method
  4769. * @category Control Flow
  4770. * @param {Array|Iterable|Object} tasks - A collection containing functions to
  4771. * run, each function is passed a `callback(err, result)` it must call on
  4772. * completion with an error `err` (which can be `null`) and an optional `result`
  4773. * value.
  4774. * @param {Function} [callback] - An optional callback which is called when one
  4775. * of the tasks has succeeded, or all have failed. It receives the `err` and
  4776. * `result` arguments of the last attempt at completing the `task`. Invoked with
  4777. * (err, results).
  4778. * @example
  4779. * async.tryEach([
  4780. * function getDataFromFirstWebsite(callback) {
  4781. * // Try getting the data from the first website
  4782. * callback(err, data);
  4783. * },
  4784. * function getDataFromSecondWebsite(callback) {
  4785. * // First website failed,
  4786. * // Try getting the data from the backup website
  4787. * callback(err, data);
  4788. * }
  4789. * ],
  4790. * // optional callback
  4791. * function(err, results) {
  4792. * Now do something with the data.
  4793. * });
  4794. *
  4795. */
  4796. function tryEach(tasks, callback) {
  4797. var error = null;
  4798. var result;
  4799. callback = callback || noop;
  4800. eachSeries(tasks, function(task, callback) {
  4801. wrapAsync(task)(function (err, res/*, ...args*/) {
  4802. if (arguments.length > 2) {
  4803. result = slice(arguments, 1);
  4804. } else {
  4805. result = res;
  4806. }
  4807. error = err;
  4808. callback(!err);
  4809. });
  4810. }, function () {
  4811. callback(error, result);
  4812. });
  4813. }
  4814. /**
  4815. * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,
  4816. * unmemoized form. Handy for testing.
  4817. *
  4818. * @name unmemoize
  4819. * @static
  4820. * @memberOf module:Utils
  4821. * @method
  4822. * @see [async.memoize]{@link module:Utils.memoize}
  4823. * @category Util
  4824. * @param {AsyncFunction} fn - the memoized function
  4825. * @returns {AsyncFunction} a function that calls the original unmemoized function
  4826. */
  4827. function unmemoize(fn) {
  4828. return function () {
  4829. return (fn.unmemoized || fn).apply(null, arguments);
  4830. };
  4831. }
  4832. /**
  4833. * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
  4834. * stopped, or an error occurs.
  4835. *
  4836. * @name whilst
  4837. * @static
  4838. * @memberOf module:ControlFlow
  4839. * @method
  4840. * @category Control Flow
  4841. * @param {Function} test - synchronous truth test to perform before each
  4842. * execution of `iteratee`. Invoked with ().
  4843. * @param {AsyncFunction} iteratee - An async function which is called each time
  4844. * `test` passes. Invoked with (callback).
  4845. * @param {Function} [callback] - A callback which is called after the test
  4846. * function has failed and repeated execution of `iteratee` has stopped. `callback`
  4847. * will be passed an error and any arguments passed to the final `iteratee`'s
  4848. * callback. Invoked with (err, [results]);
  4849. * @returns undefined
  4850. * @example
  4851. *
  4852. * var count = 0;
  4853. * async.whilst(
  4854. * function() { return count < 5; },
  4855. * function(callback) {
  4856. * count++;
  4857. * setTimeout(function() {
  4858. * callback(null, count);
  4859. * }, 1000);
  4860. * },
  4861. * function (err, n) {
  4862. * // 5 seconds have passed, n = 5
  4863. * }
  4864. * );
  4865. */
  4866. function whilst(test, iteratee, callback) {
  4867. callback = onlyOnce(callback || noop);
  4868. var _iteratee = wrapAsync(iteratee);
  4869. if (!test()) return callback(null);
  4870. var next = function(err/*, ...args*/) {
  4871. if (err) return callback(err);
  4872. if (test()) return _iteratee(next);
  4873. var args = slice(arguments, 1);
  4874. callback.apply(null, [null].concat(args));
  4875. };
  4876. _iteratee(next);
  4877. }
  4878. /**
  4879. * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when
  4880. * stopped, or an error occurs. `callback` will be passed an error and any
  4881. * arguments passed to the final `iteratee`'s callback.
  4882. *
  4883. * The inverse of [whilst]{@link module:ControlFlow.whilst}.
  4884. *
  4885. * @name until
  4886. * @static
  4887. * @memberOf module:ControlFlow
  4888. * @method
  4889. * @see [async.whilst]{@link module:ControlFlow.whilst}
  4890. * @category Control Flow
  4891. * @param {Function} test - synchronous truth test to perform before each
  4892. * execution of `iteratee`. Invoked with ().
  4893. * @param {AsyncFunction} iteratee - An async function which is called each time
  4894. * `test` fails. Invoked with (callback).
  4895. * @param {Function} [callback] - A callback which is called after the test
  4896. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  4897. * will be passed an error and any arguments passed to the final `iteratee`'s
  4898. * callback. Invoked with (err, [results]);
  4899. */
  4900. function until(test, iteratee, callback) {
  4901. whilst(function() {
  4902. return !test.apply(this, arguments);
  4903. }, iteratee, callback);
  4904. }
  4905. /**
  4906. * Runs the `tasks` array of functions in series, each passing their results to
  4907. * the next in the array. However, if any of the `tasks` pass an error to their
  4908. * own callback, the next function is not executed, and the main `callback` is
  4909. * immediately called with the error.
  4910. *
  4911. * @name waterfall
  4912. * @static
  4913. * @memberOf module:ControlFlow
  4914. * @method
  4915. * @category Control Flow
  4916. * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
  4917. * to run.
  4918. * Each function should complete with any number of `result` values.
  4919. * The `result` values will be passed as arguments, in order, to the next task.
  4920. * @param {Function} [callback] - An optional callback to run once all the
  4921. * functions have completed. This will be passed the results of the last task's
  4922. * callback. Invoked with (err, [results]).
  4923. * @returns undefined
  4924. * @example
  4925. *
  4926. * async.waterfall([
  4927. * function(callback) {
  4928. * callback(null, 'one', 'two');
  4929. * },
  4930. * function(arg1, arg2, callback) {
  4931. * // arg1 now equals 'one' and arg2 now equals 'two'
  4932. * callback(null, 'three');
  4933. * },
  4934. * function(arg1, callback) {
  4935. * // arg1 now equals 'three'
  4936. * callback(null, 'done');
  4937. * }
  4938. * ], function (err, result) {
  4939. * // result now equals 'done'
  4940. * });
  4941. *
  4942. * // Or, with named functions:
  4943. * async.waterfall([
  4944. * myFirstFunction,
  4945. * mySecondFunction,
  4946. * myLastFunction,
  4947. * ], function (err, result) {
  4948. * // result now equals 'done'
  4949. * });
  4950. * function myFirstFunction(callback) {
  4951. * callback(null, 'one', 'two');
  4952. * }
  4953. * function mySecondFunction(arg1, arg2, callback) {
  4954. * // arg1 now equals 'one' and arg2 now equals 'two'
  4955. * callback(null, 'three');
  4956. * }
  4957. * function myLastFunction(arg1, callback) {
  4958. * // arg1 now equals 'three'
  4959. * callback(null, 'done');
  4960. * }
  4961. */
  4962. var waterfall = function(tasks, callback) {
  4963. callback = once(callback || noop);
  4964. if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
  4965. if (!tasks.length) return callback();
  4966. var taskIndex = 0;
  4967. function nextTask(args) {
  4968. var task = wrapAsync(tasks[taskIndex++]);
  4969. args.push(onlyOnce(next));
  4970. task.apply(null, args);
  4971. }
  4972. function next(err/*, ...args*/) {
  4973. if (err || taskIndex === tasks.length) {
  4974. return callback.apply(null, arguments);
  4975. }
  4976. nextTask(slice(arguments, 1));
  4977. }
  4978. nextTask([]);
  4979. };
  4980. /**
  4981. * An "async function" in the context of Async is an asynchronous function with
  4982. * a variable number of parameters, with the final parameter being a callback.
  4983. * (`function (arg1, arg2, ..., callback) {}`)
  4984. * The final callback is of the form `callback(err, results...)`, which must be
  4985. * called once the function is completed. The callback should be called with a
  4986. * Error as its first argument to signal that an error occurred.
  4987. * Otherwise, if no error occurred, it should be called with `null` as the first
  4988. * argument, and any additional `result` arguments that may apply, to signal
  4989. * successful completion.
  4990. * The callback must be called exactly once, ideally on a later tick of the
  4991. * JavaScript event loop.
  4992. *
  4993. * This type of function is also referred to as a "Node-style async function",
  4994. * or a "continuation passing-style function" (CPS). Most of the methods of this
  4995. * library are themselves CPS/Node-style async functions, or functions that
  4996. * return CPS/Node-style async functions.
  4997. *
  4998. * Wherever we accept a Node-style async function, we also directly accept an
  4999. * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.
  5000. * In this case, the `async` function will not be passed a final callback
  5001. * argument, and any thrown error will be used as the `err` argument of the
  5002. * implicit callback, and the return value will be used as the `result` value.
  5003. * (i.e. a `rejected` of the returned Promise becomes the `err` callback
  5004. * argument, and a `resolved` value becomes the `result`.)
  5005. *
  5006. * Note, due to JavaScript limitations, we can only detect native `async`
  5007. * functions and not transpilied implementations.
  5008. * Your environment must have `async`/`await` support for this to work.
  5009. * (e.g. Node > v7.6, or a recent version of a modern browser).
  5010. * If you are using `async` functions through a transpiler (e.g. Babel), you
  5011. * must still wrap the function with [asyncify]{@link module:Utils.asyncify},
  5012. * because the `async function` will be compiled to an ordinary function that
  5013. * returns a promise.
  5014. *
  5015. * @typedef {Function} AsyncFunction
  5016. * @static
  5017. */
  5018. /**
  5019. * Async is a utility module which provides straight-forward, powerful functions
  5020. * for working with asynchronous JavaScript. Although originally designed for
  5021. * use with [Node.js](http://nodejs.org) and installable via
  5022. * `npm install --save async`, it can also be used directly in the browser.
  5023. * @module async
  5024. * @see AsyncFunction
  5025. */
  5026. /**
  5027. * A collection of `async` functions for manipulating collections, such as
  5028. * arrays and objects.
  5029. * @module Collections
  5030. */
  5031. /**
  5032. * A collection of `async` functions for controlling the flow through a script.
  5033. * @module ControlFlow
  5034. */
  5035. /**
  5036. * A collection of `async` utility functions.
  5037. * @module Utils
  5038. */
  5039. var index = {
  5040. apply: apply,
  5041. applyEach: applyEach,
  5042. applyEachSeries: applyEachSeries,
  5043. asyncify: asyncify,
  5044. auto: auto,
  5045. autoInject: autoInject,
  5046. cargo: cargo,
  5047. compose: compose,
  5048. concat: concat,
  5049. concatLimit: concatLimit,
  5050. concatSeries: concatSeries,
  5051. constant: constant,
  5052. detect: detect,
  5053. detectLimit: detectLimit,
  5054. detectSeries: detectSeries,
  5055. dir: dir,
  5056. doDuring: doDuring,
  5057. doUntil: doUntil,
  5058. doWhilst: doWhilst,
  5059. during: during,
  5060. each: eachLimit,
  5061. eachLimit: eachLimit$1,
  5062. eachOf: eachOf,
  5063. eachOfLimit: eachOfLimit,
  5064. eachOfSeries: eachOfSeries,
  5065. eachSeries: eachSeries,
  5066. ensureAsync: ensureAsync,
  5067. every: every,
  5068. everyLimit: everyLimit,
  5069. everySeries: everySeries,
  5070. filter: filter,
  5071. filterLimit: filterLimit,
  5072. filterSeries: filterSeries,
  5073. forever: forever,
  5074. groupBy: groupBy,
  5075. groupByLimit: groupByLimit,
  5076. groupBySeries: groupBySeries,
  5077. log: log,
  5078. map: map,
  5079. mapLimit: mapLimit,
  5080. mapSeries: mapSeries,
  5081. mapValues: mapValues,
  5082. mapValuesLimit: mapValuesLimit,
  5083. mapValuesSeries: mapValuesSeries,
  5084. memoize: memoize,
  5085. nextTick: nextTick,
  5086. parallel: parallelLimit,
  5087. parallelLimit: parallelLimit$1,
  5088. priorityQueue: priorityQueue,
  5089. queue: queue$1,
  5090. race: race,
  5091. reduce: reduce,
  5092. reduceRight: reduceRight,
  5093. reflect: reflect,
  5094. reflectAll: reflectAll,
  5095. reject: reject,
  5096. rejectLimit: rejectLimit,
  5097. rejectSeries: rejectSeries,
  5098. retry: retry,
  5099. retryable: retryable,
  5100. seq: seq,
  5101. series: series,
  5102. setImmediate: setImmediate$1,
  5103. some: some,
  5104. someLimit: someLimit,
  5105. someSeries: someSeries,
  5106. sortBy: sortBy,
  5107. timeout: timeout,
  5108. times: times,
  5109. timesLimit: timeLimit,
  5110. timesSeries: timesSeries,
  5111. transform: transform,
  5112. tryEach: tryEach,
  5113. unmemoize: unmemoize,
  5114. until: until,
  5115. waterfall: waterfall,
  5116. whilst: whilst,
  5117. // aliases
  5118. all: every,
  5119. allLimit: everyLimit,
  5120. allSeries: everySeries,
  5121. any: some,
  5122. anyLimit: someLimit,
  5123. anySeries: someSeries,
  5124. find: detect,
  5125. findLimit: detectLimit,
  5126. findSeries: detectSeries,
  5127. forEach: eachLimit,
  5128. forEachSeries: eachSeries,
  5129. forEachLimit: eachLimit$1,
  5130. forEachOf: eachOf,
  5131. forEachOfSeries: eachOfSeries,
  5132. forEachOfLimit: eachOfLimit,
  5133. inject: reduce,
  5134. foldl: reduce,
  5135. foldr: reduceRight,
  5136. select: filter,
  5137. selectLimit: filterLimit,
  5138. selectSeries: filterSeries,
  5139. wrapSync: asyncify
  5140. };
  5141. exports['default'] = index;
  5142. exports.apply = apply;
  5143. exports.applyEach = applyEach;
  5144. exports.applyEachSeries = applyEachSeries;
  5145. exports.asyncify = asyncify;
  5146. exports.auto = auto;
  5147. exports.autoInject = autoInject;
  5148. exports.cargo = cargo;
  5149. exports.compose = compose;
  5150. exports.concat = concat;
  5151. exports.concatLimit = concatLimit;
  5152. exports.concatSeries = concatSeries;
  5153. exports.constant = constant;
  5154. exports.detect = detect;
  5155. exports.detectLimit = detectLimit;
  5156. exports.detectSeries = detectSeries;
  5157. exports.dir = dir;
  5158. exports.doDuring = doDuring;
  5159. exports.doUntil = doUntil;
  5160. exports.doWhilst = doWhilst;
  5161. exports.during = during;
  5162. exports.each = eachLimit;
  5163. exports.eachLimit = eachLimit$1;
  5164. exports.eachOf = eachOf;
  5165. exports.eachOfLimit = eachOfLimit;
  5166. exports.eachOfSeries = eachOfSeries;
  5167. exports.eachSeries = eachSeries;
  5168. exports.ensureAsync = ensureAsync;
  5169. exports.every = every;
  5170. exports.everyLimit = everyLimit;
  5171. exports.everySeries = everySeries;
  5172. exports.filter = filter;
  5173. exports.filterLimit = filterLimit;
  5174. exports.filterSeries = filterSeries;
  5175. exports.forever = forever;
  5176. exports.groupBy = groupBy;
  5177. exports.groupByLimit = groupByLimit;
  5178. exports.groupBySeries = groupBySeries;
  5179. exports.log = log;
  5180. exports.map = map;
  5181. exports.mapLimit = mapLimit;
  5182. exports.mapSeries = mapSeries;
  5183. exports.mapValues = mapValues;
  5184. exports.mapValuesLimit = mapValuesLimit;
  5185. exports.mapValuesSeries = mapValuesSeries;
  5186. exports.memoize = memoize;
  5187. exports.nextTick = nextTick;
  5188. exports.parallel = parallelLimit;
  5189. exports.parallelLimit = parallelLimit$1;
  5190. exports.priorityQueue = priorityQueue;
  5191. exports.queue = queue$1;
  5192. exports.race = race;
  5193. exports.reduce = reduce;
  5194. exports.reduceRight = reduceRight;
  5195. exports.reflect = reflect;
  5196. exports.reflectAll = reflectAll;
  5197. exports.reject = reject;
  5198. exports.rejectLimit = rejectLimit;
  5199. exports.rejectSeries = rejectSeries;
  5200. exports.retry = retry;
  5201. exports.retryable = retryable;
  5202. exports.seq = seq;
  5203. exports.series = series;
  5204. exports.setImmediate = setImmediate$1;
  5205. exports.some = some;
  5206. exports.someLimit = someLimit;
  5207. exports.someSeries = someSeries;
  5208. exports.sortBy = sortBy;
  5209. exports.timeout = timeout;
  5210. exports.times = times;
  5211. exports.timesLimit = timeLimit;
  5212. exports.timesSeries = timesSeries;
  5213. exports.transform = transform;
  5214. exports.tryEach = tryEach;
  5215. exports.unmemoize = unmemoize;
  5216. exports.until = until;
  5217. exports.waterfall = waterfall;
  5218. exports.whilst = whilst;
  5219. exports.all = every;
  5220. exports.allLimit = everyLimit;
  5221. exports.allSeries = everySeries;
  5222. exports.any = some;
  5223. exports.anyLimit = someLimit;
  5224. exports.anySeries = someSeries;
  5225. exports.find = detect;
  5226. exports.findLimit = detectLimit;
  5227. exports.findSeries = detectSeries;
  5228. exports.forEach = eachLimit;
  5229. exports.forEachSeries = eachSeries;
  5230. exports.forEachLimit = eachLimit$1;
  5231. exports.forEachOf = eachOf;
  5232. exports.forEachOfSeries = eachOfSeries;
  5233. exports.forEachOfLimit = eachOfLimit;
  5234. exports.inject = reduce;
  5235. exports.foldl = reduce;
  5236. exports.foldr = reduceRight;
  5237. exports.select = filter;
  5238. exports.selectLimit = filterLimit;
  5239. exports.selectSeries = filterSeries;
  5240. exports.wrapSync = asyncify;
  5241. Object.defineProperty(exports, '__esModule', { value: true });
  5242. })));