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.

README.md 59KB

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