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.

1646 lines
51 KiB

7 years ago
  1. # Async.js
  2. [![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async)
  3. Async is a utility module which provides straight-forward, powerful functions
  4. for working with asynchronous JavaScript. Although originally designed for
  5. use with [Node.js](http://nodejs.org), it can also be used directly in the
  6. browser. Also supports [component](https://github.com/component/component).
  7. Async provides around 20 functions that include the usual 'functional'
  8. suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns
  9. for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these
  10. functions assume you follow the Node.js convention of providing a single
  11. callback as the last argument of your `async` function.
  12. ## Quick Examples
  13. ```javascript
  14. async.map(['file1','file2','file3'], fs.stat, function(err, results){
  15. // results is now an array of stats for each file
  16. });
  17. async.filter(['file1','file2','file3'], fs.exists, function(results){
  18. // results now equals an array of the existing files
  19. });
  20. async.parallel([
  21. function(){ ... },
  22. function(){ ... }
  23. ], callback);
  24. async.series([
  25. function(){ ... },
  26. function(){ ... }
  27. ]);
  28. ```
  29. There are many more functions available so take a look at the docs below for a
  30. full list. This module aims to be comprehensive, so if you feel anything is
  31. missing please create a GitHub issue for it.
  32. ## Common Pitfalls
  33. ### Binding a context to an iterator
  34. This section is really about `bind`, not about `async`. If you are wondering how to
  35. make `async` execute your iterators in a given context, or are confused as to why
  36. a method of another library isn't working as an iterator, study this example:
  37. ```js
  38. // Here is a simple object with an (unnecessarily roundabout) squaring method
  39. var AsyncSquaringLibrary = {
  40. squareExponent: 2,
  41. square: function(number, callback){
  42. var result = Math.pow(number, this.squareExponent);
  43. setTimeout(function(){
  44. callback(null, result);
  45. }, 200);
  46. }
  47. };
  48. async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){
  49. // result is [NaN, NaN, NaN]
  50. // This fails because the `this.squareExponent` expression in the square
  51. // function is not evaluated in the context of AsyncSquaringLibrary, and is
  52. // therefore undefined.
  53. });
  54. async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){
  55. // result is [1, 4, 9]
  56. // With the help of bind we can attach a context to the iterator before
  57. // passing it to async. Now the square function will be executed in its
  58. // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent`
  59. // will be as expected.
  60. });
  61. ```
  62. ## Download
  63. The source is available for download from
  64. [GitHub](http://github.com/caolan/async).
  65. Alternatively, you can install using Node Package Manager (`npm`):
  66. npm install async
  67. __Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed
  68. ## In the Browser
  69. So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5.
  70. Usage:
  71. ```html
  72. <script type="text/javascript" src="async.js"></script>
  73. <script type="text/javascript">
  74. async.map(data, asyncProcess, function(err, results){
  75. alert(results);
  76. });
  77. </script>
  78. ```
  79. ## Documentation
  80. ### Collections
  81. * [`each`](#each)
  82. * [`eachSeries`](#eachSeries)
  83. * [`eachLimit`](#eachLimit)
  84. * [`map`](#map)
  85. * [`mapSeries`](#mapSeries)
  86. * [`mapLimit`](#mapLimit)
  87. * [`filter`](#filter)
  88. * [`filterSeries`](#filterSeries)
  89. * [`reject`](#reject)
  90. * [`rejectSeries`](#rejectSeries)
  91. * [`reduce`](#reduce)
  92. * [`reduceRight`](#reduceRight)
  93. * [`detect`](#detect)
  94. * [`detectSeries`](#detectSeries)
  95. * [`sortBy`](#sortBy)
  96. * [`some`](#some)
  97. * [`every`](#every)
  98. * [`concat`](#concat)
  99. * [`concatSeries`](#concatSeries)
  100. ### Control Flow
  101. * [`series`](#seriestasks-callback)
  102. * [`parallel`](#parallel)
  103. * [`parallelLimit`](#parallellimittasks-limit-callback)
  104. * [`whilst`](#whilst)
  105. * [`doWhilst`](#doWhilst)
  106. * [`until`](#until)
  107. * [`doUntil`](#doUntil)
  108. * [`forever`](#forever)
  109. * [`waterfall`](#waterfall)
  110. * [`compose`](#compose)
  111. * [`seq`](#seq)
  112. * [`applyEach`](#applyEach)
  113. * [`applyEachSeries`](#applyEachSeries)
  114. * [`queue`](#queue)
  115. * [`priorityQueue`](#priorityQueue)
  116. * [`cargo`](#cargo)
  117. * [`auto`](#auto)
  118. * [`retry`](#retry)
  119. * [`iterator`](#iterator)
  120. * [`apply`](#apply)
  121. * [`nextTick`](#nextTick)
  122. * [`times`](#times)
  123. * [`timesSeries`](#timesSeries)
  124. ### Utils
  125. * [`memoize`](#memoize)
  126. * [`unmemoize`](#unmemoize)
  127. * [`log`](#log)
  128. * [`dir`](#dir)
  129. * [`noConflict`](#noConflict)
  130. ## Collections
  131. <a name="forEach" />
  132. <a name="each" />
  133. ### each(arr, iterator, callback)
  134. Applies the function `iterator` to each item in `arr`, in parallel.
  135. The `iterator` is called with an item from the list, and a callback for when it
  136. has finished. If the `iterator` passes an error to its `callback`, the main
  137. `callback` (for the `each` function) is immediately called with the error.
  138. Note, that since this function applies `iterator` to each item in parallel,
  139. there is no guarantee that the iterator functions will complete in order.
  140. __Arguments__
  141. * `arr` - An array to iterate over.
  142. * `iterator(item, callback)` - A function to apply to each item in `arr`.
  143. The iterator is passed a `callback(err)` which must be called once it has
  144. completed. If no error has occured, the `callback` should be run without
  145. arguments or with an explicit `null` argument.
  146. * `callback(err)` - A callback which is called when all `iterator` functions
  147. have finished, or an error occurs.
  148. __Examples__
  149. ```js
  150. // assuming openFiles is an array of file names and saveFile is a function
  151. // to save the modified contents of that file:
  152. async.each(openFiles, saveFile, function(err){
  153. // if any of the saves produced an error, err would equal that error
  154. });
  155. ```
  156. ```js
  157. // assuming openFiles is an array of file names
  158. async.each(openFiles, function( file, callback) {
  159. // Perform operation on file here.
  160. console.log('Processing file ' + file);
  161. if( file.length > 32 ) {
  162. console.log('This file name is too long');
  163. callback('File name too long');
  164. } else {
  165. // Do work to process file here
  166. console.log('File processed');
  167. callback();
  168. }
  169. }, function(err){
  170. // if any of the file processing produced an error, err would equal that error
  171. if( err ) {
  172. // One of the iterations produced an error.
  173. // All processing will now stop.
  174. console.log('A file failed to process');
  175. } else {
  176. console.log('All files have been processed successfully');
  177. }
  178. });
  179. ```
  180. ---------------------------------------
  181. <a name="forEachSeries" />
  182. <a name="eachSeries" />
  183. ### eachSeries(arr, iterator, callback)
  184. The same as [`each`](#each), only `iterator` is applied to each item in `arr` in
  185. series. The next `iterator` is only called once the current one has completed.
  186. This means the `iterator` functions will complete in order.
  187. ---------------------------------------
  188. <a name="forEachLimit" />
  189. <a name="eachLimit" />
  190. ### eachLimit(arr, limit, iterator, callback)
  191. The same as [`each`](#each), only no more than `limit` `iterator`s will be simultaneously
  192. running at any time.
  193. Note that the items in `arr` are not processed in batches, so there is no guarantee that
  194. the first `limit` `iterator` functions will complete before any others are started.
  195. __Arguments__
  196. * `arr` - An array to iterate over.
  197. * `limit` - The maximum number of `iterator`s to run at any time.
  198. * `iterator(item, callback)` - A function to apply to each item in `arr`.
  199. The iterator is passed a `callback(err)` which must be called once it has
  200. completed. If no error has occured, the callback should be run without
  201. arguments or with an explicit `null` argument.
  202. * `callback(err)` - A callback which is called when all `iterator` functions
  203. have finished, or an error occurs.
  204. __Example__
  205. ```js
  206. // Assume documents is an array of JSON objects and requestApi is a
  207. // function that interacts with a rate-limited REST api.
  208. async.eachLimit(documents, 20, requestApi, function(err){
  209. // if any of the saves produced an error, err would equal that error
  210. });
  211. ```
  212. ---------------------------------------
  213. <a name="map" />
  214. ### map(arr, iterator, callback)
  215. Produces a new array of values by mapping each value in `arr` through
  216. the `iterator` function. The `iterator` is called with an item from `arr` and a
  217. callback for when it has finished processing. Each of these callback takes 2 arguments:
  218. an `error`, and the transformed item from `arr`. If `iterator` passes an error to this
  219. callback, the main `callback` (for the `map` function) is immediately called with the error.
  220. Note, that since this function applies the `iterator` to each item in parallel,
  221. there is no guarantee that the `iterator` functions will complete in order.
  222. However, the results array will be in the same order as the original `arr`.
  223. __Arguments__
  224. * `arr` - An array to iterate over.
  225. * `iterator(item, callback)` - A function to apply to each item in `arr`.
  226. The iterator is passed a `callback(err, transformed)` which must be called once
  227. it has completed with an error (which can be `null`) and a transformed item.
  228. * `callback(err, results)` - A callback which is called when all `iterator`
  229. functions have finished, or an error occurs. Results is an array of the
  230. transformed items from the `arr`.
  231. __Example__
  232. ```js
  233. async.map(['file1','file2','file3'], fs.stat, function(err, results){
  234. // results is now an array of stats for each file
  235. });
  236. ```
  237. ---------------------------------------
  238. <a name="mapSeries" />
  239. ### mapSeries(arr, iterator, callback)
  240. The same as [`map`](#map), only the `iterator` is applied to each item in `arr` in
  241. series. The next `iterator` is only called once the current one has completed.
  242. The results array will be in the same order as the original.
  243. ---------------------------------------
  244. <a name="mapLimit" />
  245. ### mapLimit(arr, limit, iterator, callback)
  246. The same as [`map`](#map), only no more than `limit` `iterator`s will be simultaneously
  247. running at any time.
  248. Note that the items are not processed in batches, so there is no guarantee that
  249. the first `limit` `iterator` functions will complete before any others are started.
  250. __Arguments__
  251. * `arr` - An array to iterate over.
  252. * `limit` - The maximum number of `iterator`s to run at any time.
  253. * `iterator(item, callback)` - A function to apply to each item in `arr`.
  254. The iterator is passed a `callback(err, transformed)` which must be called once
  255. it has completed with an error (which can be `null`) and a transformed item.
  256. * `callback(err, results)` - A callback which is called when all `iterator`
  257. calls have finished, or an error occurs. The result is an array of the
  258. transformed items from the original `arr`.
  259. __Example__
  260. ```js
  261. async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){
  262. // results is now an array of stats for each file
  263. });
  264. ```
  265. ---------------------------------------
  266. <a name="select" />
  267. <a name="filter" />
  268. ### filter(arr, iterator, callback)
  269. __Alias:__ `select`
  270. Returns a new array of all the values in `arr` which pass an async truth test.
  271. _The callback for each `iterator` call only accepts a single argument of `true` or
  272. `false`; it does not accept an error argument first!_ This is in-line with the
  273. way node libraries work with truth tests like `fs.exists`. This operation is
  274. performed in parallel, but the results array will be in the same order as the
  275. original.
  276. __Arguments__
  277. * `arr` - An array to iterate over.
  278. * `iterator(item, callback)` - A truth test to apply to each item in `arr`.
  279. The `iterator` is passed a `callback(truthValue)`, which must be called with a
  280. boolean argument once it has completed.
  281. * `callback(results)` - A callback which is called after all the `iterator`
  282. functions have finished.
  283. __Example__
  284. ```js
  285. async.filter(['file1','file2','file3'], fs.exists, function(results){
  286. // results now equals an array of the existing files
  287. });
  288. ```
  289. ---------------------------------------
  290. <a name="selectSeries" />
  291. <a name="filterSeries" />
  292. ### filterSeries(arr, iterator, callback)
  293. __Alias:__ `selectSeries`
  294. The same as [`filter`](#filter) only the `iterator` is applied to each item in `arr` in
  295. series. The next `iterator` is only called once the current one has completed.
  296. The results array will be in the same order as the original.
  297. ---------------------------------------
  298. <a name="reject" />
  299. ### reject(arr, iterator, callback)
  300. The opposite of [`filter`](#filter). Removes values that pass an `async` truth test.
  301. ---------------------------------------
  302. <a name="rejectSeries" />
  303. ### rejectSeries(arr, iterator, callback)
  304. The same as [`reject`](#reject), only the `iterator` is applied to each item in `arr`
  305. in series.
  306. ---------------------------------------
  307. <a name="reduce" />
  308. ### reduce(arr, memo, iterator, callback)
  309. __Aliases:__ `inject`, `foldl`
  310. Reduces `arr` into a single value using an async `iterator` to return
  311. each successive step. `memo` is the initial state of the reduction.
  312. This function only operates in series.
  313. For performance reasons, it may make sense to split a call to this function into
  314. a parallel map, and then use the normal `Array.prototype.reduce` on the results.
  315. This function is for situations where each step in the reduction needs to be async;
  316. if you can get the data before reducing it, then it's probably a good idea to do so.
  317. __Arguments__
  318. * `arr` - An array to iterate over.
  319. * `memo` - The initial state of the reduction.
  320. * `iterator(memo, item, callback)` - A function applied to each item in the
  321. array to produce the next step in the reduction. The `iterator` is passed a
  322. `callback(err, reduction)` which accepts an optional error as its first
  323. argument, and the state of the reduction as the second. If an error is
  324. passed to the callback, the reduction is stopped and the main `callback` is
  325. immediately called with the error.
  326. * `callback(err, result)` - A callback which is called after all the `iterator`
  327. functions have finished. Result is the reduced value.
  328. __Example__
  329. ```js
  330. async.reduce([1,2,3], 0, function(memo, item, callback){
  331. // pointless async:
  332. process.nextTick(function(){
  333. callback(null, memo + item)
  334. });
  335. }, function(err, result){
  336. // result is now equal to the last value of memo, which is 6
  337. });
  338. ```
  339. ---------------------------------------
  340. <a name="reduceRight" />
  341. ### reduceRight(arr, memo, iterator, callback)
  342. __Alias:__ `foldr`
  343. Same as [`reduce`](#reduce), only operates on `arr` in reverse order.
  344. ---------------------------------------
  345. <a name="detect" />
  346. ### detect(arr, iterator, callback)
  347. Returns the first value in `arr` that passes an async truth test. The
  348. `iterator` is applied in parallel, meaning the first iterator to return `true` will
  349. fire the detect `callback` with that result. That means the result might not be
  350. the first item in the original `arr` (in terms of order) that passes the test.
  351. If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries).
  352. __Arguments__
  353. * `arr` - An array to iterate over.
  354. * `iterator(item, callback)` - A truth test to apply to each item in `arr`.
  355. The iterator is passed a `callback(truthValue)` which must be called with a
  356. boolean argument once it has completed.
  357. * `callback(result)` - A callback which is called as soon as any iterator returns
  358. `true`, or after all the `iterator` functions have finished. Result will be
  359. the first item in the array that passes the truth test (iterator) or the
  360. value `undefined` if none passed.
  361. __Example__
  362. ```js
  363. async.detect(['file1','file2','file3'], fs.exists, function(result){
  364. // result now equals the first file in the list that exists
  365. });
  366. ```
  367. ---------------------------------------
  368. <a name="detectSeries" />
  369. ### detectSeries(arr, iterator, callback)
  370. The same as [`detect`](#detect), only the `iterator` is applied to each item in `arr`
  371. in series. This means the result is always the first in the original `arr` (in
  372. terms of array order) that passes the truth test.
  373. ---------------------------------------
  374. <a name="sortBy" />
  375. ### sortBy(arr, iterator, callback)
  376. Sorts a list by the results of running each `arr` value through an async `iterator`.
  377. __Arguments__
  378. * `arr` - An array to iterate over.
  379. * `iterator(item, callback)` - A function to apply to each item in `arr`.
  380. The iterator is passed a `callback(err, sortValue)` which must be called once it
  381. has completed with an error (which can be `null`) and a value to use as the sort
  382. criteria.
  383. * `callback(err, results)` - A callback which is called after all the `iterator`
  384. functions have finished, or an error occurs. Results is the items from
  385. the original `arr` sorted by the values returned by the `iterator` calls.
  386. __Example__
  387. ```js
  388. async.sortBy(['file1','file2','file3'], function(file, callback){
  389. fs.stat(file, function(err, stats){
  390. callback(err, stats.mtime);
  391. });
  392. }, function(err, results){
  393. // results is now the original array of files sorted by
  394. // modified date
  395. });
  396. ```
  397. __Sort Order__
  398. By modifying the callback parameter the sorting order can be influenced:
  399. ```js
  400. //ascending order
  401. async.sortBy([1,9,3,5], function(x, callback){
  402. callback(err, x);
  403. }, function(err,result){
  404. //result callback
  405. } );
  406. //descending order
  407. async.sortBy([1,9,3,5], function(x, callback){
  408. callback(err, x*-1); //<- x*-1 instead of x, turns the order around
  409. }, function(err,result){
  410. //result callback
  411. } );
  412. ```
  413. ---------------------------------------
  414. <a name="some" />
  415. ### some(arr, iterator, callback)
  416. __Alias:__ `any`
  417. Returns `true` if at least one element in the `arr` satisfies an async test.
  418. _The callback for each iterator call only accepts a single argument of `true` or
  419. `false`; it does not accept an error argument first!_ This is in-line with the
  420. way node libraries work with truth tests like `fs.exists`. Once any iterator
  421. call returns `true`, the main `callback` is immediately called.
  422. __Arguments__
  423. * `arr` - An array to iterate over.
  424. * `iterator(item, callback)` - A truth test to apply to each item in the array
  425. in parallel. The iterator is passed a callback(truthValue) which must be
  426. called with a boolean argument once it has completed.
  427. * `callback(result)` - A callback which is called as soon as any iterator returns
  428. `true`, or after all the iterator functions have finished. Result will be
  429. either `true` or `false` depending on the values of the async tests.
  430. __Example__
  431. ```js
  432. async.some(['file1','file2','file3'], fs.exists, function(result){
  433. // if result is true then at least one of the files exists
  434. });
  435. ```
  436. ---------------------------------------
  437. <a name="every" />
  438. ### every(arr, iterator, callback)
  439. __Alias:__ `all`
  440. Returns `true` if every element in `arr` satisfies an async test.
  441. _The callback for each `iterator` call only accepts a single argument of `true` or
  442. `false`; it does not accept an error argument first!_ This is in-line with the
  443. way node libraries work with truth tests like `fs.exists`.
  444. __Arguments__
  445. * `arr` - An array to iterate over.
  446. * `iterator(item, callback)` - A truth test to apply to each item in the array
  447. in parallel. The iterator is passed a callback(truthValue) which must be
  448. called with a boolean argument once it has completed.
  449. * `callback(result)` - A callback which is called after all the `iterator`
  450. functions have finished. Result will be either `true` or `false` depending on
  451. the values of the async tests.
  452. __Example__
  453. ```js
  454. async.every(['file1','file2','file3'], fs.exists, function(result){
  455. // if result is true then every file exists
  456. });
  457. ```
  458. ---------------------------------------
  459. <a name="concat" />
  460. ### concat(arr, iterator, callback)
  461. Applies `iterator` to each item in `arr`, concatenating the results. Returns the
  462. concatenated list. The `iterator`s are called in parallel, and the results are
  463. concatenated as they return. There is no guarantee that the results array will
  464. be returned in the original order of `arr` passed to the `iterator` function.
  465. __Arguments__
  466. * `arr` - An array to iterate over.
  467. * `iterator(item, callback)` - A function to apply to each item in `arr`.
  468. The iterator is passed a `callback(err, results)` which must be called once it
  469. has completed with an error (which can be `null`) and an array of results.
  470. * `callback(err, results)` - A callback which is called after all the `iterator`
  471. functions have finished, or an error occurs. Results is an array containing
  472. the concatenated results of the `iterator` function.
  473. __Example__
  474. ```js
  475. async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
  476. // files is now a list of filenames that exist in the 3 directories
  477. });
  478. ```
  479. ---------------------------------------
  480. <a name="concatSeries" />
  481. ### concatSeries(arr, iterator, callback)
  482. Same as [`concat`](#concat), but executes in series instead of parallel.
  483. ## Control Flow
  484. <a name="series" />
  485. ### series(tasks, [callback])
  486. Run the functions in the `tasks` array in series, each one running once the previous
  487. function has completed. If any functions in the series pass an error to its
  488. callback, no more functions are run, and `callback` is immediately called with the value of the error.
  489. Otherwise, `callback` receives an array of results when `tasks` have completed.
  490. It is also possible to use an object instead of an array. Each property will be
  491. run as a function, and the results will be passed to the final `callback` as an object
  492. instead of an array. This can be a more readable way of handling results from
  493. [`series`](#series).
  494. **Note** that while many implementations preserve the order of object properties, the
  495. [ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
  496. explicitly states that
  497. > The mechanics and order of enumerating the properties is not specified.
  498. So if you rely on the order in which your series of functions are executed, and want
  499. this to work on all platforms, consider using an array.
  500. __Arguments__
  501. * `tasks` - An array or object containing functions to run, each function is passed
  502. a `callback(err, result)` it must call on completion with an error `err` (which can
  503. be `null`) and an optional `result` value.
  504. * `callback(err, results)` - An optional callback to run once all the functions
  505. have completed. This function gets a results array (or object) containing all
  506. the result arguments passed to the `task` callbacks.
  507. __Example__
  508. ```js
  509. async.series([
  510. function(callback){
  511. // do some stuff ...
  512. callback(null, 'one');
  513. },
  514. function(callback){
  515. // do some more stuff ...
  516. callback(null, 'two');
  517. }
  518. ],
  519. // optional callback
  520. function(err, results){
  521. // results is now equal to ['one', 'two']
  522. });
  523. // an example using an object instead of an array
  524. async.series({
  525. one: function(callback){
  526. setTimeout(function(){
  527. callback(null, 1);
  528. }, 200);
  529. },
  530. two: function(callback){
  531. setTimeout(function(){
  532. callback(null, 2);
  533. }, 100);
  534. }
  535. },
  536. function(err, results) {
  537. // results is now equal to: {one: 1, two: 2}
  538. });
  539. ```
  540. ---------------------------------------
  541. <a name="parallel" />
  542. ### parallel(tasks, [callback])
  543. Run the `tasks` array of functions in parallel, without waiting until the previous
  544. function has completed. If any of the functions pass an error to its
  545. callback, the main `callback` is immediately called with the value of the error.
  546. Once the `tasks` have completed, the results are passed to the final `callback` as an
  547. array.
  548. It is also possible to use an object instead of an array. Each property will be
  549. run as a function and the results will be passed to the final `callback` as an object
  550. instead of an array. This can be a more readable way of handling results from
  551. [`parallel`](#parallel).
  552. __Arguments__
  553. * `tasks` - An array or object containing functions to run. Each function is passed
  554. a `callback(err, result)` which it must call on completion with an error `err`
  555. (which can be `null`) and an optional `result` value.
  556. * `callback(err, results)` - An optional callback to run once all the functions
  557. have completed. This function gets a results array (or object) containing all
  558. the result arguments passed to the task callbacks.
  559. __Example__
  560. ```js
  561. async.parallel([
  562. function(callback){
  563. setTimeout(function(){
  564. callback(null, 'one');
  565. }, 200);
  566. },
  567. function(callback){
  568. setTimeout(function(){
  569. callback(null, 'two');
  570. }, 100);
  571. }
  572. ],
  573. // optional callback
  574. function(err, results){
  575. // the results array will equal ['one','two'] even though
  576. // the second function had a shorter timeout.
  577. });
  578. // an example using an object instead of an array
  579. async.parallel({
  580. one: function(callback){
  581. setTimeout(function(){
  582. callback(null, 1);
  583. }, 200);
  584. },
  585. two: function(callback){
  586. setTimeout(function(){
  587. callback(null, 2);
  588. }, 100);
  589. }
  590. },
  591. function(err, results) {
  592. // results is now equals to: {one: 1, two: 2}
  593. });
  594. ```
  595. ---------------------------------------
  596. <a name="parallelLimit" />
  597. ### parallelLimit(tasks, limit, [callback])
  598. The same as [`parallel`](#parallel), only `tasks` are executed in parallel
  599. with a maximum of `limit` tasks executing at any time.
  600. Note that the `tasks` are not executed in batches, so there is no guarantee that
  601. the first `limit` tasks will complete before any others are started.
  602. __Arguments__
  603. * `tasks` - An array or object containing functions to run, each function is passed
  604. a `callback(err, result)` it must call on completion with an error `err` (which can
  605. be `null`) and an optional `result` value.
  606. * `limit` - The maximum number of `tasks` to run at any time.
  607. * `callback(err, results)` - An optional callback to run once all the functions
  608. have completed. This function gets a results array (or object) containing all
  609. the result arguments passed to the `task` callbacks.
  610. ---------------------------------------
  611. <a name="whilst" />
  612. ### whilst(test, fn, callback)
  613. Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped,
  614. or an error occurs.
  615. __Arguments__
  616. * `test()` - synchronous truth test to perform before each execution of `fn`.
  617. * `fn(callback)` - A function which is called each time `test` passes. The function is
  618. passed a `callback(err)`, which must be called once it has completed with an
  619. optional `err` argument.
  620. * `callback(err)` - A callback which is called after the test fails and repeated
  621. execution of `fn` has stopped.
  622. __Example__
  623. ```js
  624. var count = 0;
  625. async.whilst(
  626. function () { return count < 5; },
  627. function (callback) {
  628. count++;
  629. setTimeout(callback, 1000);
  630. },
  631. function (err) {
  632. // 5 seconds have passed
  633. }
  634. );
  635. ```
  636. ---------------------------------------
  637. <a name="doWhilst" />
  638. ### doWhilst(fn, test, callback)
  639. The post-check version of [`whilst`](#whilst). To reflect the difference in
  640. the order of operations, the arguments `test` and `fn` are switched.
  641. `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
  642. ---------------------------------------
  643. <a name="until" />
  644. ### until(test, fn, callback)
  645. Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped,
  646. or an error occurs.
  647. The inverse of [`whilst`](#whilst).
  648. ---------------------------------------
  649. <a name="doUntil" />
  650. ### doUntil(fn, test, callback)
  651. Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`.
  652. ---------------------------------------
  653. <a name="forever" />
  654. ### forever(fn, errback)
  655. Calls the asynchronous function `fn` with a callback parameter that allows it to
  656. call itself again, in series, indefinitely.
  657. If an error is passed to the callback then `errback` is called with the
  658. error, and execution stops, otherwise it will never be called.
  659. ```js
  660. async.forever(
  661. function(next) {
  662. // next is suitable for passing to things that need a callback(err [, whatever]);
  663. // it will result in this function being called again.
  664. },
  665. function(err) {
  666. // if next is called with a value in its first parameter, it will appear
  667. // in here as 'err', and execution will stop.
  668. }
  669. );
  670. ```
  671. ---------------------------------------
  672. <a name="waterfall" />
  673. ### waterfall(tasks, [callback])
  674. Runs the `tasks` array of functions in series, each passing their results to the next in
  675. the array. However, if any of the `tasks` pass an error to their own callback, the
  676. next function is not executed, and the main `callback` is immediately called with
  677. the error.
  678. __Arguments__
  679. * `tasks` - An array of functions to run, each function is passed a
  680. `callback(err, result1, result2, ...)` it must call on completion. The first
  681. argument is an error (which can be `null`) and any further arguments will be
  682. passed as arguments in order to the next task.
  683. * `callback(err, [results])` - An optional callback to run once all the functions
  684. have completed. This will be passed the results of the last task's callback.
  685. __Example__
  686. ```js
  687. async.waterfall([
  688. function(callback){
  689. callback(null, 'one', 'two');
  690. },
  691. function(arg1, arg2, callback){
  692. // arg1 now equals 'one' and arg2 now equals 'two'
  693. callback(null, 'three');
  694. },
  695. function(arg1, callback){
  696. // arg1 now equals 'three'
  697. callback(null, 'done');
  698. }
  699. ], function (err, result) {
  700. // result now equals 'done'
  701. });
  702. ```
  703. ---------------------------------------
  704. <a name="compose" />
  705. ### compose(fn1, fn2...)
  706. Creates a function which is a composition of the passed asynchronous
  707. functions. Each function consumes the return value of the function that
  708. follows. Composing functions `f()`, `g()`, and `h()` would produce the result of
  709. `f(g(h()))`, only this version uses callbacks to obtain the return values.
  710. Each function is executed with the `this` binding of the composed function.
  711. __Arguments__
  712. * `functions...` - the asynchronous functions to compose
  713. __Example__
  714. ```js
  715. function add1(n, callback) {
  716. setTimeout(function () {
  717. callback(null, n + 1);
  718. }, 10);
  719. }
  720. function mul3(n, callback) {
  721. setTimeout(function () {
  722. callback(null, n * 3);
  723. }, 10);
  724. }
  725. var add1mul3 = async.compose(mul3, add1);
  726. add1mul3(4, function (err, result) {
  727. // result now equals 15
  728. });
  729. ```
  730. ---------------------------------------
  731. <a name="seq" />
  732. ### seq(fn1, fn2...)
  733. Version of the compose function that is more natural to read.
  734. Each following function consumes the return value of the latter function.
  735. Each function is executed with the `this` binding of the composed function.
  736. __Arguments__
  737. * functions... - the asynchronous functions to compose
  738. __Example__
  739. ```js
  740. // Requires lodash (or underscore), express3 and dresende's orm2.
  741. // Part of an app, that fetches cats of the logged user.
  742. // This example uses `seq` function to avoid overnesting and error
  743. // handling clutter.
  744. app.get('/cats', function(request, response) {
  745. function handleError(err, data, callback) {
  746. if (err) {
  747. console.error(err);
  748. response.json({ status: 'error', message: err.message });
  749. }
  750. else {
  751. callback(data);
  752. }
  753. }
  754. var User = request.models.User;
  755. async.seq(
  756. _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
  757. handleError,
  758. function(user, fn) {
  759. user.getCats(fn); // 'getCats' has signature (callback(err, data))
  760. },
  761. handleError,
  762. function(cats) {
  763. response.json({ status: 'ok', message: 'Cats found', data: cats });
  764. }
  765. )(req.session.user_id);
  766. }
  767. });
  768. ```
  769. ---------------------------------------
  770. <a name="applyEach" />
  771. ### applyEach(fns, args..., callback)
  772. Applies the provided arguments to each function in the array, calling
  773. `callback` after all functions have completed. If you only provide the first
  774. argument, then it will return a function which lets you pass in the
  775. arguments as if it were a single function call.
  776. __Arguments__
  777. * `fns` - the asynchronous functions to all call with the same arguments
  778. * `args...` - any number of separate arguments to pass to the function
  779. * `callback` - the final argument should be the callback, called when all
  780. functions have completed processing
  781. __Example__
  782. ```js
  783. async.applyEach([enableSearch, updateSchema], 'bucket', callback);
  784. // partial application example:
  785. async.each(
  786. buckets,
  787. async.applyEach([enableSearch, updateSchema]),
  788. callback
  789. );
  790. ```
  791. ---------------------------------------
  792. <a name="applyEachSeries" />
  793. ### applyEachSeries(arr, iterator, callback)
  794. The same as [`applyEach`](#applyEach) only the functions are applied in series.
  795. ---------------------------------------
  796. <a name="queue" />
  797. ### queue(worker, concurrency)
  798. Creates a `queue` object with the specified `concurrency`. Tasks added to the
  799. `queue` are processed in parallel (up to the `concurrency` limit). If all
  800. `worker`s are in progress, the task is queued until one becomes available.
  801. Once a `worker` completes a `task`, that `task`'s callback is called.
  802. __Arguments__
  803. * `worker(task, callback)` - An asynchronous function for processing a queued
  804. task, which must call its `callback(err)` argument when finished, with an
  805. optional `error` as an argument.
  806. * `concurrency` - An `integer` for determining how many `worker` functions should be
  807. run in parallel.
  808. __Queue objects__
  809. The `queue` object returned by this function has the following properties and
  810. methods:
  811. * `length()` - a function returning the number of items waiting to be processed.
  812. * `started` - a function returning whether or not any items have been pushed and processed by the queue
  813. * `running()` - a function returning the number of items currently being processed.
  814. * `idle()` - a function returning false if there are items waiting or being processed, or true if not.
  815. * `concurrency` - an integer for determining how many `worker` functions should be
  816. run in parallel. This property can be changed after a `queue` is created to
  817. alter the concurrency on-the-fly.
  818. * `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once
  819. the `worker` has finished processing the task. Instead of a single task, a `tasks` array
  820. can be submitted. The respective callback is used for every task in the list.
  821. * `unshift(task, [callback])` - add a new task to the front of the `queue`.
  822. * `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit,
  823. and further tasks will be queued.
  824. * `empty` - a callback that is called when the last item from the `queue` is given to a `worker`.
  825. * `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`.
  826. * `paused` - a boolean for determining whether the queue is in a paused state
  827. * `pause()` - a function that pauses the processing of tasks until `resume()` is called.
  828. * `resume()` - a function that resumes the processing of queued tasks when the queue is paused.
  829. * `kill()` - a function that empties remaining tasks from the queue forcing it to go idle.
  830. __Example__
  831. ```js
  832. // create a queue object with concurrency 2
  833. var q = async.queue(function (task, callback) {
  834. console.log('hello ' + task.name);
  835. callback();
  836. }, 2);
  837. // assign a callback
  838. q.drain = function() {
  839. console.log('all items have been processed');
  840. }
  841. // add some items to the queue
  842. q.push({name: 'foo'}, function (err) {
  843. console.log('finished processing foo');
  844. });
  845. q.push({name: 'bar'}, function (err) {
  846. console.log('finished processing bar');
  847. });
  848. // add some items to the queue (batch-wise)
  849. q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {
  850. console.log('finished processing bar');
  851. });
  852. // add some items to the front of the queue
  853. q.unshift({name: 'bar'}, function (err) {
  854. console.log('finished processing bar');
  855. });
  856. ```
  857. ---------------------------------------
  858. <a name="priorityQueue" />
  859. ### priorityQueue(worker, concurrency)
  860. The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects:
  861. * `push(task, priority, [callback])` - `priority` should be a number. If an array of
  862. `tasks` is given, all tasks will be assigned the same priority.
  863. * The `unshift` method was removed.
  864. ---------------------------------------
  865. <a name="cargo" />
  866. ### cargo(worker, [payload])
  867. Creates a `cargo` object with the specified payload. Tasks added to the
  868. cargo will be processed altogether (up to the `payload` limit). If the
  869. `worker` is in progress, the task is queued until it becomes available. Once
  870. the `worker` has completed some tasks, each callback of those tasks is called.
  871. Check out [this animation](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) for how `cargo` and `queue` work.
  872. While [queue](#queue) passes only one task to one of a group of workers
  873. at a time, cargo passes an array of tasks to a single worker, repeating
  874. when the worker is finished.
  875. __Arguments__
  876. * `worker(tasks, callback)` - An asynchronous function for processing an array of
  877. queued tasks, which must call its `callback(err)` argument when finished, with
  878. an optional `err` argument.
  879. * `payload` - An optional `integer` for determining how many tasks should be
  880. processed per round; if omitted, the default is unlimited.
  881. __Cargo objects__
  882. The `cargo` object returned by this function has the following properties and
  883. methods:
  884. * `length()` - A function returning the number of items waiting to be processed.
  885. * `payload` - An `integer` for determining how many tasks should be
  886. process per round. This property can be changed after a `cargo` is created to
  887. alter the payload on-the-fly.
  888. * `push(task, [callback])` - Adds `task` to the `queue`. The callback is called
  889. once the `worker` has finished processing the task. Instead of a single task, an array of `tasks`
  890. can be submitted. The respective callback is used for every task in the list.
  891. * `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued.
  892. * `empty` - A callback that is called when the last item from the `queue` is given to a `worker`.
  893. * `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`.
  894. __Example__
  895. ```js
  896. // create a cargo object with payload 2
  897. var cargo = async.cargo(function (tasks, callback) {
  898. for(var i=0; i<tasks.length; i++){
  899. console.log('hello ' + tasks[i].name);
  900. }
  901. callback();
  902. }, 2);
  903. // add some items
  904. cargo.push({name: 'foo'}, function (err) {
  905. console.log('finished processing foo');
  906. });
  907. cargo.push({name: 'bar'}, function (err) {
  908. console.log('finished processing bar');
  909. });
  910. cargo.push({name: 'baz'}, function (err) {
  911. console.log('finished processing baz');
  912. });
  913. ```
  914. ---------------------------------------
  915. <a name="auto" />
  916. ### auto(tasks, [callback])
  917. Determines the best order for running the functions in `tasks`, based on their
  918. requirements. Each function can optionally depend on other functions being completed
  919. first, and each function is run as soon as its requirements are satisfied.
  920. If any of the functions pass an error to their callback, it will not
  921. complete (so any other functions depending on it will not run), and the main
  922. `callback` is immediately called with the error. Functions also receive an
  923. object containing the results of functions which have completed so far.
  924. Note, all functions are called with a `results` object as a second argument,
  925. so it is unsafe to pass functions in the `tasks` object which cannot handle the
  926. extra argument.
  927. For example, this snippet of code:
  928. ```js
  929. async.auto({
  930. readData: async.apply(fs.readFile, 'data.txt', 'utf-8')
  931. }, callback);
  932. ```
  933. will have the effect of calling `readFile` with the results object as the last
  934. argument, which will fail:
  935. ```js
  936. fs.readFile('data.txt', 'utf-8', cb, {});
  937. ```
  938. Instead, wrap the call to `readFile` in a function which does not forward the
  939. `results` object:
  940. ```js
  941. async.auto({
  942. readData: function(cb, results){
  943. fs.readFile('data.txt', 'utf-8', cb);
  944. }
  945. }, callback);
  946. ```
  947. __Arguments__
  948. * `tasks` - An object. Each of its properties is either a function or an array of
  949. requirements, with the function itself the last item in the array. The object's key
  950. of a property serves as the name of the task defined by that property,
  951. i.e. can be used when specifying requirements for other tasks.
  952. The function receives two arguments: (1) a `callback(err, result)` which must be
  953. called when finished, passing an `error` (which can be `null`) and the result of
  954. the function's execution, and (2) a `results` object, containing the results of
  955. the previously executed functions.
  956. * `callback(err, results)` - An optional callback which is called when all the
  957. tasks have been completed. It receives the `err` argument if any `tasks`
  958. pass an error to their callback. Results are always returned; however, if
  959. an error occurs, no further `tasks` will be performed, and the results
  960. object will only contain partial results.
  961. __Example__
  962. ```js
  963. async.auto({
  964. get_data: function(callback){
  965. console.log('in get_data');
  966. // async code to get some data
  967. callback(null, 'data', 'converted to array');
  968. },
  969. make_folder: function(callback){
  970. console.log('in make_folder');
  971. // async code to create a directory to store a file in
  972. // this is run at the same time as getting the data
  973. callback(null, 'folder');
  974. },
  975. write_file: ['get_data', 'make_folder', function(callback, results){
  976. console.log('in write_file', JSON.stringify(results));
  977. // once there is some data and the directory exists,
  978. // write the data to a file in the directory
  979. callback(null, 'filename');
  980. }],
  981. email_link: ['write_file', function(callback, results){
  982. console.log('in email_link', JSON.stringify(results));
  983. // once the file is written let's email a link to it...
  984. // results.write_file contains the filename returned by write_file.
  985. callback(null, {'file':results.write_file, 'email':'user@example.com'});
  986. }]
  987. }, function(err, results) {
  988. console.log('err = ', err);
  989. console.log('results = ', results);
  990. });
  991. ```
  992. This is a fairly trivial example, but to do this using the basic parallel and
  993. series functions would look like this:
  994. ```js
  995. async.parallel([
  996. function(callback){
  997. console.log('in get_data');
  998. // async code to get some data
  999. callback(null, 'data', 'converted to array');
  1000. },
  1001. function(callback){
  1002. console.log('in make_folder');
  1003. // async code to create a directory to store a file in
  1004. // this is run at the same time as getting the data
  1005. callback(null, 'folder');
  1006. }
  1007. ],
  1008. function(err, results){
  1009. async.series([
  1010. function(callback){
  1011. console.log('in write_file', JSON.stringify(results));
  1012. // once there is some data and the directory exists,
  1013. // write the data to a file in the directory
  1014. results.push('filename');
  1015. callback(null);
  1016. },
  1017. function(callback){
  1018. console.log('in email_link', JSON.stringify(results));
  1019. // once the file is written let's email a link to it...
  1020. callback(null, {'file':results.pop(), 'email':'user@example.com'});
  1021. }
  1022. ]);
  1023. });
  1024. ```
  1025. For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding
  1026. new tasks much easier (and the code more readable).
  1027. ---------------------------------------
  1028. <a name="retry" />
  1029. ### retry([times = 5], task, [callback])
  1030. Attempts to get a successful response from `task` no more than `times` times before
  1031. returning an error. If the task is successful, the `callback` will be passed the result
  1032. of the successfull task. If all attemps fail, the callback will be passed the error and
  1033. result (if any) of the final attempt.
  1034. __Arguments__
  1035. * `times` - An integer indicating how many times to attempt the `task` before giving up. Defaults to 5.
  1036. * `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)`
  1037. which must be called when finished, passing `err` (which can be `null`) and the `result` of
  1038. the function's execution, and (2) a `results` object, containing the results of
  1039. the previously executed functions (if nested inside another control flow).
  1040. * `callback(err, results)` - An optional callback which is called when the
  1041. task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`.
  1042. The [`retry`](#retry) function can be used as a stand-alone control flow by passing a
  1043. callback, as shown below:
  1044. ```js
  1045. async.retry(3, apiMethod, function(err, result) {
  1046. // do something with the result
  1047. });
  1048. ```
  1049. It can also be embeded within other control flow functions to retry individual methods
  1050. that are not as reliable, like this:
  1051. ```js
  1052. async.auto({
  1053. users: api.getUsers.bind(api),
  1054. payments: async.retry(3, api.getPayments.bind(api))
  1055. }, function(err, results) {
  1056. // do something with the results
  1057. });
  1058. ```
  1059. ---------------------------------------
  1060. <a name="iterator" />
  1061. ### iterator(tasks)
  1062. Creates an iterator function which calls the next function in the `tasks` array,
  1063. returning a continuation to call the next one after that. It's also possible to
  1064. “peek” at the next iterator with `iterator.next()`.
  1065. This function is used internally by the `async` module, but can be useful when
  1066. you want to manually control the flow of functions in series.
  1067. __Arguments__
  1068. * `tasks` - An array of functions to run.
  1069. __Example__
  1070. ```js
  1071. var iterator = async.iterator([
  1072. function(){ sys.p('one'); },
  1073. function(){ sys.p('two'); },
  1074. function(){ sys.p('three'); }
  1075. ]);
  1076. node> var iterator2 = iterator();
  1077. 'one'
  1078. node> var iterator3 = iterator2();
  1079. 'two'
  1080. node> iterator3();
  1081. 'three'
  1082. node> var nextfn = iterator2.next();
  1083. node> nextfn();
  1084. 'three'
  1085. ```
  1086. ---------------------------------------
  1087. <a name="apply" />
  1088. ### apply(function, arguments..)
  1089. Creates a continuation function with some arguments already applied.
  1090. Useful as a shorthand when combined with other control flow functions. Any arguments
  1091. passed to the returned function are added to the arguments originally passed
  1092. to apply.
  1093. __Arguments__
  1094. * `function` - The function you want to eventually apply all arguments to.
  1095. * `arguments...` - Any number of arguments to automatically apply when the
  1096. continuation is called.
  1097. __Example__
  1098. ```js
  1099. // using apply
  1100. async.parallel([
  1101. async.apply(fs.writeFile, 'testfile1', 'test1'),
  1102. async.apply(fs.writeFile, 'testfile2', 'test2'),
  1103. ]);
  1104. // the same process without using apply
  1105. async.parallel([
  1106. function(callback){
  1107. fs.writeFile('testfile1', 'test1', callback);
  1108. },
  1109. function(callback){
  1110. fs.writeFile('testfile2', 'test2', callback);
  1111. }
  1112. ]);
  1113. ```
  1114. It's possible to pass any number of additional arguments when calling the
  1115. continuation:
  1116. ```js
  1117. node> var fn = async.apply(sys.puts, 'one');
  1118. node> fn('two', 'three');
  1119. one
  1120. two
  1121. three
  1122. ```
  1123. ---------------------------------------
  1124. <a name="nextTick" />
  1125. ### nextTick(callback)
  1126. Calls `callback` on a later loop around the event loop. In Node.js this just
  1127. calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)`
  1128. if available, otherwise `setTimeout(callback, 0)`, which means other higher priority
  1129. events may precede the execution of `callback`.
  1130. This is used internally for browser-compatibility purposes.
  1131. __Arguments__
  1132. * `callback` - The function to call on a later loop around the event loop.
  1133. __Example__
  1134. ```js
  1135. var call_order = [];
  1136. async.nextTick(function(){
  1137. call_order.push('two');
  1138. // call_order now equals ['one','two']
  1139. });
  1140. call_order.push('one')
  1141. ```
  1142. <a name="times" />
  1143. ### times(n, callback)
  1144. Calls the `callback` function `n` times, and accumulates results in the same manner
  1145. you would use with [`map`](#map).
  1146. __Arguments__
  1147. * `n` - The number of times to run the function.
  1148. * `callback` - The function to call `n` times.
  1149. __Example__
  1150. ```js
  1151. // Pretend this is some complicated async factory
  1152. var createUser = function(id, callback) {
  1153. callback(null, {
  1154. id: 'user' + id
  1155. })
  1156. }
  1157. // generate 5 users
  1158. async.times(5, function(n, next){
  1159. createUser(n, function(err, user) {
  1160. next(err, user)
  1161. })
  1162. }, function(err, users) {
  1163. // we should now have 5 users
  1164. });
  1165. ```
  1166. <a name="timesSeries" />
  1167. ### timesSeries(n, callback)
  1168. The same as [`times`](#times), only the iterator is applied to each item in `arr` in
  1169. series. The next `iterator` is only called once the current one has completed.
  1170. The results array will be in the same order as the original.
  1171. ## Utils
  1172. <a name="memoize" />
  1173. ### memoize(fn, [hasher])
  1174. Caches the results of an `async` function. When creating a hash to store function
  1175. results against, the callback is omitted from the hash and an optional hash
  1176. function can be used.
  1177. The cache of results is exposed as the `memo` property of the function returned
  1178. by `memoize`.
  1179. __Arguments__
  1180. * `fn` - The function to proxy and cache results from.
  1181. * `hasher` - Tn optional function for generating a custom hash for storing
  1182. results. It has all the arguments applied to it apart from the callback, and
  1183. must be synchronous.
  1184. __Example__
  1185. ```js
  1186. var slow_fn = function (name, callback) {
  1187. // do something
  1188. callback(null, result);
  1189. };
  1190. var fn = async.memoize(slow_fn);
  1191. // fn can now be used as if it were slow_fn
  1192. fn('some name', function () {
  1193. // callback
  1194. });
  1195. ```
  1196. <a name="unmemoize" />
  1197. ### unmemoize(fn)
  1198. Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized
  1199. form. Handy for testing.
  1200. __Arguments__
  1201. * `fn` - the memoized function
  1202. <a name="log" />
  1203. ### log(function, arguments)
  1204. Logs the result of an `async` function to the `console`. Only works in Node.js or
  1205. in browsers that support `console.log` and `console.error` (such as FF and Chrome).
  1206. If multiple arguments are returned from the async function, `console.log` is
  1207. called on each argument in order.
  1208. __Arguments__
  1209. * `function` - The function you want to eventually apply all arguments to.
  1210. * `arguments...` - Any number of arguments to apply to the function.
  1211. __Example__
  1212. ```js
  1213. var hello = function(name, callback){
  1214. setTimeout(function(){
  1215. callback(null, 'hello ' + name);
  1216. }, 1000);
  1217. };
  1218. ```
  1219. ```js
  1220. node> async.log(hello, 'world');
  1221. 'hello world'
  1222. ```
  1223. ---------------------------------------
  1224. <a name="dir" />
  1225. ### dir(function, arguments)
  1226. Logs the result of an `async` function to the `console` using `console.dir` to
  1227. display the properties of the resulting object. Only works in Node.js or
  1228. in browsers that support `console.dir` and `console.error` (such as FF and Chrome).
  1229. If multiple arguments are returned from the async function, `console.dir` is
  1230. called on each argument in order.
  1231. __Arguments__
  1232. * `function` - The function you want to eventually apply all arguments to.
  1233. * `arguments...` - Any number of arguments to apply to the function.
  1234. __Example__
  1235. ```js
  1236. var hello = function(name, callback){
  1237. setTimeout(function(){
  1238. callback(null, {hello: name});
  1239. }, 1000);
  1240. };
  1241. ```
  1242. ```js
  1243. node> async.dir(hello, 'world');
  1244. {hello: 'world'}
  1245. ```
  1246. ---------------------------------------
  1247. <a name="noConflict" />
  1248. ### noConflict()
  1249. Changes the value of `async` back to its original value, returning a reference to the
  1250. `async` object.