3 [![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async)
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.
11 Async is also installable via:
13 - [bower](http://bower.io/): `bower install async`
14 - [component](https://github.com/component/component): `component install
16 - [jam](http://jamjs.org/): `jam install async`
17 - [spm](http://spmjs.io/): `spm install async`
19 Async provides around 20 functions that include the usual 'functional'
20 suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns
21 for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these
22 functions assume you follow the Node.js convention of providing a single
23 callback as the last argument of your `async` function.
29 async.map(['file1','file2','file3'], fs.stat, function(err, results){
30 // results is now an array of stats for each file
33 async.filter(['file1','file2','file3'], fs.exists, function(results){
34 // results now equals an array of the existing files
48 There are many more functions available so take a look at the docs below for a
49 full list. This module aims to be comprehensive, so if you feel anything is
50 missing please create a GitHub issue for it.
54 ### Binding a context to an iterator
56 This section is really about `bind`, not about `async`. If you are wondering how to
57 make `async` execute your iterators in a given context, or are confused as to why
58 a method of another library isn't working as an iterator, study this example:
61 // Here is a simple object with an (unnecessarily roundabout) squaring method
62 var AsyncSquaringLibrary = {
64 square: function(number, callback){
65 var result = Math.pow(number, this.squareExponent);
66 setTimeout(function(){
67 callback(null, result);
72 async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){
73 // result is [NaN, NaN, NaN]
74 // This fails because the `this.squareExponent` expression in the square
75 // function is not evaluated in the context of AsyncSquaringLibrary, and is
76 // therefore undefined.
79 async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){
80 // result is [1, 4, 9]
81 // With the help of bind we can attach a context to the iterator before
82 // passing it to async. Now the square function will be executed in its
83 // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent`
84 // will be as expected.
90 The source is available for download from
91 [GitHub](http://github.com/caolan/async).
92 Alternatively, you can install using Node Package Manager (`npm`):
96 __Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed
100 So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5.
105 <script type="text/javascript" src="async.js"></script>
106 <script type="text/javascript">
108 async.map(data, asyncProcess, function(err, results){
120 * [`eachSeries`](#eachSeries)
121 * [`eachLimit`](#eachLimit)
123 * [`mapSeries`](#mapSeries)
124 * [`mapLimit`](#mapLimit)
125 * [`filter`](#filter)
126 * [`filterSeries`](#filterSeries)
127 * [`reject`](#reject)
128 * [`rejectSeries`](#rejectSeries)
129 * [`reduce`](#reduce)
130 * [`reduceRight`](#reduceRight)
131 * [`detect`](#detect)
132 * [`detectSeries`](#detectSeries)
133 * [`sortBy`](#sortBy)
136 * [`concat`](#concat)
137 * [`concatSeries`](#concatSeries)
141 * [`series`](#seriestasks-callback)
142 * [`parallel`](#parallel)
143 * [`parallelLimit`](#parallellimittasks-limit-callback)
144 * [`whilst`](#whilst)
145 * [`doWhilst`](#doWhilst)
147 * [`doUntil`](#doUntil)
148 * [`forever`](#forever)
149 * [`waterfall`](#waterfall)
150 * [`compose`](#compose)
152 * [`applyEach`](#applyEach)
153 * [`applyEachSeries`](#applyEachSeries)
155 * [`priorityQueue`](#priorityQueue)
159 * [`iterator`](#iterator)
161 * [`nextTick`](#nextTick)
163 * [`timesSeries`](#timesSeries)
167 * [`memoize`](#memoize)
168 * [`unmemoize`](#unmemoize)
171 * [`noConflict`](#noConflict)
178 ### each(arr, iterator, callback)
180 Applies the function `iterator` to each item in `arr`, in parallel.
181 The `iterator` is called with an item from the list, and a callback for when it
182 has finished. If the `iterator` passes an error to its `callback`, the main
183 `callback` (for the `each` function) is immediately called with the error.
185 Note, that since this function applies `iterator` to each item in parallel,
186 there is no guarantee that the iterator functions will complete in order.
190 * `arr` - An array to iterate over.
191 * `iterator(item, callback)` - A function to apply to each item in `arr`.
192 The iterator is passed a `callback(err)` which must be called once it has
193 completed. If no error has occurred, the `callback` should be run without
194 arguments or with an explicit `null` argument.
195 * `callback(err)` - A callback which is called when all `iterator` functions
196 have finished, or an error occurs.
202 // assuming openFiles is an array of file names and saveFile is a function
203 // to save the modified contents of that file:
205 async.each(openFiles, saveFile, function(err){
206 // if any of the saves produced an error, err would equal that error
211 // assuming openFiles is an array of file names
213 async.each(openFiles, function(file, callback) {
215 // Perform operation on file here.
216 console.log('Processing file ' + file);
218 if( file.length > 32 ) {
219 console.log('This file name is too long');
220 callback('File name too long');
222 // Do work to process file here
223 console.log('File processed');
227 // if any of the file processing produced an error, err would equal that error
229 // One of the iterations produced an error.
230 // All processing will now stop.
231 console.log('A file failed to process');
233 console.log('All files have been processed successfully');
238 ---------------------------------------
240 <a name="forEachSeries" />
241 <a name="eachSeries" />
242 ### eachSeries(arr, iterator, callback)
244 The same as [`each`](#each), only `iterator` is applied to each item in `arr` in
245 series. The next `iterator` is only called once the current one has completed.
246 This means the `iterator` functions will complete in order.
249 ---------------------------------------
251 <a name="forEachLimit" />
252 <a name="eachLimit" />
253 ### eachLimit(arr, limit, iterator, callback)
255 The same as [`each`](#each), only no more than `limit` `iterator`s will be simultaneously
258 Note that the items in `arr` are not processed in batches, so there is no guarantee that
259 the first `limit` `iterator` functions will complete before any others are started.
263 * `arr` - An array to iterate over.
264 * `limit` - The maximum number of `iterator`s to run at any time.
265 * `iterator(item, callback)` - A function to apply to each item in `arr`.
266 The iterator is passed a `callback(err)` which must be called once it has
267 completed. If no error has occurred, the callback should be run without
268 arguments or with an explicit `null` argument.
269 * `callback(err)` - A callback which is called when all `iterator` functions
270 have finished, or an error occurs.
275 // Assume documents is an array of JSON objects and requestApi is a
276 // function that interacts with a rate-limited REST api.
278 async.eachLimit(documents, 20, requestApi, function(err){
279 // if any of the saves produced an error, err would equal that error
283 ---------------------------------------
286 ### map(arr, iterator, callback)
288 Produces a new array of values by mapping each value in `arr` through
289 the `iterator` function. The `iterator` is called with an item from `arr` and a
290 callback for when it has finished processing. Each of these callback takes 2 arguments:
291 an `error`, and the transformed item from `arr`. If `iterator` passes an error to his
292 callback, the main `callback` (for the `map` function) is immediately called with the error.
294 Note, that since this function applies the `iterator` to each item in parallel,
295 there is no guarantee that the `iterator` functions will complete in order.
296 However, the results array will be in the same order as the original `arr`.
300 * `arr` - An array to iterate over.
301 * `iterator(item, callback)` - A function to apply to each item in `arr`.
302 The iterator is passed a `callback(err, transformed)` which must be called once
303 it has completed with an error (which can be `null`) and a transformed item.
304 * `callback(err, results)` - A callback which is called when all `iterator`
305 functions have finished, or an error occurs. Results is an array of the
306 transformed items from the `arr`.
311 async.map(['file1','file2','file3'], fs.stat, function(err, results){
312 // results is now an array of stats for each file
316 ---------------------------------------
318 <a name="mapSeries" />
319 ### mapSeries(arr, iterator, callback)
321 The same as [`map`](#map), only the `iterator` is applied to each item in `arr` in
322 series. The next `iterator` is only called once the current one has completed.
323 The results array will be in the same order as the original.
326 ---------------------------------------
328 <a name="mapLimit" />
329 ### mapLimit(arr, limit, iterator, callback)
331 The same as [`map`](#map), only no more than `limit` `iterator`s will be simultaneously
334 Note that the items are not processed in batches, so there is no guarantee that
335 the first `limit` `iterator` functions will complete before any others are started.
339 * `arr` - An array to iterate over.
340 * `limit` - The maximum number of `iterator`s to run at any time.
341 * `iterator(item, callback)` - A function to apply to each item in `arr`.
342 The iterator is passed a `callback(err, transformed)` which must be called once
343 it has completed with an error (which can be `null`) and a transformed item.
344 * `callback(err, results)` - A callback which is called when all `iterator`
345 calls have finished, or an error occurs. The result is an array of the
346 transformed items from the original `arr`.
351 async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){
352 // results is now an array of stats for each file
356 ---------------------------------------
360 ### filter(arr, iterator, callback)
364 Returns a new array of all the values in `arr` which pass an async truth test.
365 _The callback for each `iterator` call only accepts a single argument of `true` or
366 `false`; it does not accept an error argument first!_ This is in-line with the
367 way node libraries work with truth tests like `fs.exists`. This operation is
368 performed in parallel, but the results array will be in the same order as the
373 * `arr` - An array to iterate over.
374 * `iterator(item, callback)` - A truth test to apply to each item in `arr`.
375 The `iterator` is passed a `callback(truthValue)`, which must be called with a
376 boolean argument once it has completed.
377 * `callback(results)` - A callback which is called after all the `iterator`
378 functions have finished.
383 async.filter(['file1','file2','file3'], fs.exists, function(results){
384 // results now equals an array of the existing files
388 ---------------------------------------
390 <a name="selectSeries" />
391 <a name="filterSeries" />
392 ### filterSeries(arr, iterator, callback)
394 __Alias:__ `selectSeries`
396 The same as [`filter`](#filter) only the `iterator` is applied to each item in `arr` in
397 series. The next `iterator` is only called once the current one has completed.
398 The results array will be in the same order as the original.
400 ---------------------------------------
403 ### reject(arr, iterator, callback)
405 The opposite of [`filter`](#filter). Removes values that pass an `async` truth test.
407 ---------------------------------------
409 <a name="rejectSeries" />
410 ### rejectSeries(arr, iterator, callback)
412 The same as [`reject`](#reject), only the `iterator` is applied to each item in `arr`
416 ---------------------------------------
419 ### reduce(arr, memo, iterator, callback)
421 __Aliases:__ `inject`, `foldl`
423 Reduces `arr` into a single value using an async `iterator` to return
424 each successive step. `memo` is the initial state of the reduction.
425 This function only operates in series.
427 For performance reasons, it may make sense to split a call to this function into
428 a parallel map, and then use the normal `Array.prototype.reduce` on the results.
429 This function is for situations where each step in the reduction needs to be async;
430 if you can get the data before reducing it, then it's probably a good idea to do so.
434 * `arr` - An array to iterate over.
435 * `memo` - The initial state of the reduction.
436 * `iterator(memo, item, callback)` - A function applied to each item in the
437 array to produce the next step in the reduction. The `iterator` is passed a
438 `callback(err, reduction)` which accepts an optional error as its first
439 argument, and the state of the reduction as the second. If an error is
440 passed to the callback, the reduction is stopped and the main `callback` is
441 immediately called with the error.
442 * `callback(err, result)` - A callback which is called after all the `iterator`
443 functions have finished. Result is the reduced value.
448 async.reduce([1,2,3], 0, function(memo, item, callback){
450 process.nextTick(function(){
451 callback(null, memo + item)
453 }, function(err, result){
454 // result is now equal to the last value of memo, which is 6
458 ---------------------------------------
460 <a name="reduceRight" />
461 ### reduceRight(arr, memo, iterator, callback)
465 Same as [`reduce`](#reduce), only operates on `arr` in reverse order.
468 ---------------------------------------
471 ### detect(arr, iterator, callback)
473 Returns the first value in `arr` that passes an async truth test. The
474 `iterator` is applied in parallel, meaning the first iterator to return `true` will
475 fire the detect `callback` with that result. That means the result might not be
476 the first item in the original `arr` (in terms of order) that passes the test.
478 If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries).
482 * `arr` - An array to iterate over.
483 * `iterator(item, callback)` - A truth test to apply to each item in `arr`.
484 The iterator is passed a `callback(truthValue)` which must be called with a
485 boolean argument once it has completed.
486 * `callback(result)` - A callback which is called as soon as any iterator returns
487 `true`, or after all the `iterator` functions have finished. Result will be
488 the first item in the array that passes the truth test (iterator) or the
489 value `undefined` if none passed.
494 async.detect(['file1','file2','file3'], fs.exists, function(result){
495 // result now equals the first file in the list that exists
499 ---------------------------------------
501 <a name="detectSeries" />
502 ### detectSeries(arr, iterator, callback)
504 The same as [`detect`](#detect), only the `iterator` is applied to each item in `arr`
505 in series. This means the result is always the first in the original `arr` (in
506 terms of array order) that passes the truth test.
509 ---------------------------------------
512 ### sortBy(arr, iterator, callback)
514 Sorts a list by the results of running each `arr` value through an async `iterator`.
518 * `arr` - An array to iterate over.
519 * `iterator(item, callback)` - A function to apply to each item in `arr`.
520 The iterator is passed a `callback(err, sortValue)` which must be called once it
521 has completed with an error (which can be `null`) and a value to use as the sort
523 * `callback(err, results)` - A callback which is called after all the `iterator`
524 functions have finished, or an error occurs. Results is the items from
525 the original `arr` sorted by the values returned by the `iterator` calls.
530 async.sortBy(['file1','file2','file3'], function(file, callback){
531 fs.stat(file, function(err, stats){
532 callback(err, stats.mtime);
534 }, function(err, results){
535 // results is now the original array of files sorted by
542 By modifying the callback parameter the sorting order can be influenced:
546 async.sortBy([1,9,3,5], function(x, callback){
548 }, function(err,result){
553 async.sortBy([1,9,3,5], function(x, callback){
554 callback(null, x*-1); //<- x*-1 instead of x, turns the order around
555 }, function(err,result){
560 ---------------------------------------
563 ### some(arr, iterator, callback)
567 Returns `true` if at least one element in the `arr` satisfies an async test.
568 _The callback for each iterator call only accepts a single argument of `true` or
569 `false`; it does not accept an error argument first!_ This is in-line with the
570 way node libraries work with truth tests like `fs.exists`. Once any iterator
571 call returns `true`, the main `callback` is immediately called.
575 * `arr` - An array to iterate over.
576 * `iterator(item, callback)` - A truth test to apply to each item in the array
577 in parallel. The iterator is passed a callback(truthValue) which must be
578 called with a boolean argument once it has completed.
579 * `callback(result)` - A callback which is called as soon as any iterator returns
580 `true`, or after all the iterator functions have finished. Result will be
581 either `true` or `false` depending on the values of the async tests.
586 async.some(['file1','file2','file3'], fs.exists, function(result){
587 // if result is true then at least one of the files exists
591 ---------------------------------------
594 ### every(arr, iterator, callback)
598 Returns `true` if every element in `arr` satisfies an async test.
599 _The callback for each `iterator` call only accepts a single argument of `true` or
600 `false`; it does not accept an error argument first!_ This is in-line with the
601 way node libraries work with truth tests like `fs.exists`.
605 * `arr` - An array to iterate over.
606 * `iterator(item, callback)` - A truth test to apply to each item in the array
607 in parallel. The iterator is passed a callback(truthValue) which must be
608 called with a boolean argument once it has completed.
609 * `callback(result)` - A callback which is called after all the `iterator`
610 functions have finished. Result will be either `true` or `false` depending on
611 the values of the async tests.
616 async.every(['file1','file2','file3'], fs.exists, function(result){
617 // if result is true then every file exists
621 ---------------------------------------
624 ### concat(arr, iterator, callback)
626 Applies `iterator` to each item in `arr`, concatenating the results. Returns the
627 concatenated list. The `iterator`s are called in parallel, and the results are
628 concatenated as they return. There is no guarantee that the results array will
629 be returned in the original order of `arr` passed to the `iterator` function.
633 * `arr` - An array to iterate over.
634 * `iterator(item, callback)` - A function to apply to each item in `arr`.
635 The iterator is passed a `callback(err, results)` which must be called once it
636 has completed with an error (which can be `null`) and an array of results.
637 * `callback(err, results)` - A callback which is called after all the `iterator`
638 functions have finished, or an error occurs. Results is an array containing
639 the concatenated results of the `iterator` function.
644 async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
645 // files is now a list of filenames that exist in the 3 directories
649 ---------------------------------------
651 <a name="concatSeries" />
652 ### concatSeries(arr, iterator, callback)
654 Same as [`concat`](#concat), but executes in series instead of parallel.
660 ### series(tasks, [callback])
662 Run the functions in the `tasks` array in series, each one running once the previous
663 function has completed. If any functions in the series pass an error to its
664 callback, no more functions are run, and `callback` is immediately called with the value of the error.
665 Otherwise, `callback` receives an array of results when `tasks` have completed.
667 It is also possible to use an object instead of an array. Each property will be
668 run as a function, and the results will be passed to the final `callback` as an object
669 instead of an array. This can be a more readable way of handling results from
672 **Note** that while many implementations preserve the order of object properties, the
673 [ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
674 explicitly states that
676 > The mechanics and order of enumerating the properties is not specified.
678 So if you rely on the order in which your series of functions are executed, and want
679 this to work on all platforms, consider using an array.
683 * `tasks` - An array or object containing functions to run, each function is passed
684 a `callback(err, result)` it must call on completion with an error `err` (which can
685 be `null`) and an optional `result` value.
686 * `callback(err, results)` - An optional callback to run once all the functions
687 have completed. This function gets a results array (or object) containing all
688 the result arguments passed to the `task` callbacks.
696 callback(null, 'one');
699 // do some more stuff ...
700 callback(null, 'two');
704 function(err, results){
705 // results is now equal to ['one', 'two']
709 // an example using an object instead of an array
711 one: function(callback){
712 setTimeout(function(){
716 two: function(callback){
717 setTimeout(function(){
722 function(err, results) {
723 // results is now equal to: {one: 1, two: 2}
727 ---------------------------------------
729 <a name="parallel" />
730 ### parallel(tasks, [callback])
732 Run the `tasks` array of functions in parallel, without waiting until the previous
733 function has completed. If any of the functions pass an error to its
734 callback, the main `callback` is immediately called with the value of the error.
735 Once the `tasks` have completed, the results are passed to the final `callback` as an
738 It is also possible to use an object instead of an array. Each property will be
739 run as a function and the results will be passed to the final `callback` as an object
740 instead of an array. This can be a more readable way of handling results from
741 [`parallel`](#parallel).
746 * `tasks` - An array or object containing functions to run. Each function is passed
747 a `callback(err, result)` which it must call on completion with an error `err`
748 (which can be `null`) and an optional `result` value.
749 * `callback(err, results)` - An optional callback to run once all the functions
750 have completed. This function gets a results array (or object) containing all
751 the result arguments passed to the task callbacks.
758 setTimeout(function(){
759 callback(null, 'one');
763 setTimeout(function(){
764 callback(null, 'two');
769 function(err, results){
770 // the results array will equal ['one','two'] even though
771 // the second function had a shorter timeout.
775 // an example using an object instead of an array
777 one: function(callback){
778 setTimeout(function(){
782 two: function(callback){
783 setTimeout(function(){
788 function(err, results) {
789 // results is now equals to: {one: 1, two: 2}
793 ---------------------------------------
795 <a name="parallelLimit" />
796 ### parallelLimit(tasks, limit, [callback])
798 The same as [`parallel`](#parallel), only `tasks` are executed in parallel
799 with a maximum of `limit` tasks executing at any time.
801 Note that the `tasks` are not executed in batches, so there is no guarantee that
802 the first `limit` tasks will complete before any others are started.
806 * `tasks` - An array or object containing functions to run, each function is passed
807 a `callback(err, result)` it must call on completion with an error `err` (which can
808 be `null`) and an optional `result` value.
809 * `limit` - The maximum number of `tasks` to run at any time.
810 * `callback(err, results)` - An optional callback to run once all the functions
811 have completed. This function gets a results array (or object) containing all
812 the result arguments passed to the `task` callbacks.
814 ---------------------------------------
817 ### whilst(test, fn, callback)
819 Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped,
824 * `test()` - synchronous truth test to perform before each execution of `fn`.
825 * `fn(callback)` - A function which is called each time `test` passes. The function is
826 passed a `callback(err)`, which must be called once it has completed with an
827 optional `err` argument.
828 * `callback(err)` - A callback which is called after the test fails and repeated
829 execution of `fn` has stopped.
837 function () { return count < 5; },
838 function (callback) {
840 setTimeout(callback, 1000);
843 // 5 seconds have passed
848 ---------------------------------------
850 <a name="doWhilst" />
851 ### doWhilst(fn, test, callback)
853 The post-check version of [`whilst`](#whilst). To reflect the difference in
854 the order of operations, the arguments `test` and `fn` are switched.
856 `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
858 ---------------------------------------
861 ### until(test, fn, callback)
863 Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped,
866 The inverse of [`whilst`](#whilst).
868 ---------------------------------------
871 ### doUntil(fn, test, callback)
873 Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`.
875 ---------------------------------------
878 ### forever(fn, errback)
880 Calls the asynchronous function `fn` with a callback parameter that allows it to
881 call itself again, in series, indefinitely.
883 If an error is passed to the callback then `errback` is called with the
884 error, and execution stops, otherwise it will never be called.
889 // next is suitable for passing to things that need a callback(err [, whatever]);
890 // it will result in this function being called again.
893 // if next is called with a value in its first parameter, it will appear
894 // in here as 'err', and execution will stop.
899 ---------------------------------------
901 <a name="waterfall" />
902 ### waterfall(tasks, [callback])
904 Runs the `tasks` array of functions in series, each passing their results to the next in
905 the array. However, if any of the `tasks` pass an error to their own callback, the
906 next function is not executed, and the main `callback` is immediately called with
911 * `tasks` - An array of functions to run, each function is passed a
912 `callback(err, result1, result2, ...)` it must call on completion. The first
913 argument is an error (which can be `null`) and any further arguments will be
914 passed as arguments in order to the next task.
915 * `callback(err, [results])` - An optional callback to run once all the functions
916 have completed. This will be passed the results of the last task's callback.
925 callback(null, 'one', 'two');
927 function(arg1, arg2, callback) {
928 // arg1 now equals 'one' and arg2 now equals 'two'
929 callback(null, 'three');
931 function(arg1, callback) {
932 // arg1 now equals 'three'
933 callback(null, 'done');
935 ], function (err, result) {
936 // result now equals 'done'
940 ---------------------------------------
942 ### compose(fn1, fn2...)
944 Creates a function which is a composition of the passed asynchronous
945 functions. Each function consumes the return value of the function that
946 follows. Composing functions `f()`, `g()`, and `h()` would produce the result of
947 `f(g(h()))`, only this version uses callbacks to obtain the return values.
949 Each function is executed with the `this` binding of the composed function.
953 * `functions...` - the asynchronous functions to compose
959 function add1(n, callback) {
960 setTimeout(function () {
961 callback(null, n + 1);
965 function mul3(n, callback) {
966 setTimeout(function () {
967 callback(null, n * 3);
971 var add1mul3 = async.compose(mul3, add1);
973 add1mul3(4, function (err, result) {
974 // result now equals 15
978 ---------------------------------------
982 Version of the compose function that is more natural to read.
983 Each function consumes the return value of the previous function.
984 It is the equivalent of [`compose`](#compose) with the arguments reversed.
986 Each function is executed with the `this` binding of the composed function.
990 * functions... - the asynchronous functions to compose
996 // Requires lodash (or underscore), express3 and dresende's orm2.
997 // Part of an app, that fetches cats of the logged user.
998 // This example uses `seq` function to avoid overnesting and error
1000 app.get('/cats', function(request, response) {
1001 var User = request.models.User;
1003 _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
1004 function(user, fn) {
1005 user.getCats(fn); // 'getCats' has signature (callback(err, data))
1007 )(req.session.user_id, function (err, cats) {
1010 response.json({ status: 'error', message: err.message });
1012 response.json({ status: 'ok', message: 'Cats found', data: cats });
1018 ---------------------------------------
1019 <a name="applyEach" />
1020 ### applyEach(fns, args..., callback)
1022 Applies the provided arguments to each function in the array, calling
1023 `callback` after all functions have completed. If you only provide the first
1024 argument, then it will return a function which lets you pass in the
1025 arguments as if it were a single function call.
1029 * `fns` - the asynchronous functions to all call with the same arguments
1030 * `args...` - any number of separate arguments to pass to the function
1031 * `callback` - the final argument should be the callback, called when all
1032 functions have completed processing
1038 async.applyEach([enableSearch, updateSchema], 'bucket', callback);
1040 // partial application example:
1043 async.applyEach([enableSearch, updateSchema]),
1048 ---------------------------------------
1050 <a name="applyEachSeries" />
1051 ### applyEachSeries(arr, iterator, callback)
1053 The same as [`applyEach`](#applyEach) only the functions are applied in series.
1055 ---------------------------------------
1058 ### queue(worker, concurrency)
1060 Creates a `queue` object with the specified `concurrency`. Tasks added to the
1061 `queue` are processed in parallel (up to the `concurrency` limit). If all
1062 `worker`s are in progress, the task is queued until one becomes available.
1063 Once a `worker` completes a `task`, that `task`'s callback is called.
1067 * `worker(task, callback)` - An asynchronous function for processing a queued
1068 task, which must call its `callback(err)` argument when finished, with an
1069 optional `error` as an argument.
1070 * `concurrency` - An `integer` for determining how many `worker` functions should be
1075 The `queue` object returned by this function has the following properties and
1078 * `length()` - a function returning the number of items waiting to be processed.
1079 * `started` - a function returning whether or not any items have been pushed and processed by the queue
1080 * `running()` - a function returning the number of items currently being processed.
1081 * `idle()` - a function returning false if there are items waiting or being processed, or true if not.
1082 * `concurrency` - an integer for determining how many `worker` functions should be
1083 run in parallel. This property can be changed after a `queue` is created to
1084 alter the concurrency on-the-fly.
1085 * `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once
1086 the `worker` has finished processing the task. Instead of a single task, a `tasks` array
1087 can be submitted. The respective callback is used for every task in the list.
1088 * `unshift(task, [callback])` - add a new task to the front of the `queue`.
1089 * `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit,
1090 and further tasks will be queued.
1091 * `empty` - a callback that is called when the last item from the `queue` is given to a `worker`.
1092 * `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`.
1093 * `paused` - a boolean for determining whether the queue is in a paused state
1094 * `pause()` - a function that pauses the processing of tasks until `resume()` is called.
1095 * `resume()` - a function that resumes the processing of queued tasks when the queue is paused.
1096 * `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle.
1101 // create a queue object with concurrency 2
1103 var q = async.queue(function (task, callback) {
1104 console.log('hello ' + task.name);
1109 // assign a callback
1110 q.drain = function() {
1111 console.log('all items have been processed');
1114 // add some items to the queue
1116 q.push({name: 'foo'}, function (err) {
1117 console.log('finished processing foo');
1119 q.push({name: 'bar'}, function (err) {
1120 console.log('finished processing bar');
1123 // add some items to the queue (batch-wise)
1125 q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {
1126 console.log('finished processing item');
1129 // add some items to the front of the queue
1131 q.unshift({name: 'bar'}, function (err) {
1132 console.log('finished processing bar');
1137 ---------------------------------------
1139 <a name="priorityQueue" />
1140 ### priorityQueue(worker, concurrency)
1142 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:
1144 * `push(task, priority, [callback])` - `priority` should be a number. If an array of
1145 `tasks` is given, all tasks will be assigned the same priority.
1146 * The `unshift` method was removed.
1148 ---------------------------------------
1151 ### cargo(worker, [payload])
1153 Creates a `cargo` object with the specified payload. Tasks added to the
1154 cargo will be processed altogether (up to the `payload` limit). If the
1155 `worker` is in progress, the task is queued until it becomes available. Once
1156 the `worker` has completed some tasks, each callback of those tasks is called.
1157 Check out [this animation](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) for how `cargo` and `queue` work.
1159 While [queue](#queue) passes only one task to one of a group of workers
1160 at a time, cargo passes an array of tasks to a single worker, repeating
1161 when the worker is finished.
1165 * `worker(tasks, callback)` - An asynchronous function for processing an array of
1166 queued tasks, which must call its `callback(err)` argument when finished, with
1167 an optional `err` argument.
1168 * `payload` - An optional `integer` for determining how many tasks should be
1169 processed per round; if omitted, the default is unlimited.
1173 The `cargo` object returned by this function has the following properties and
1176 * `length()` - A function returning the number of items waiting to be processed.
1177 * `payload` - An `integer` for determining how many tasks should be
1178 process per round. This property can be changed after a `cargo` is created to
1179 alter the payload on-the-fly.
1180 * `push(task, [callback])` - Adds `task` to the `queue`. The callback is called
1181 once the `worker` has finished processing the task. Instead of a single task, an array of `tasks`
1182 can be submitted. The respective callback is used for every task in the list.
1183 * `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued.
1184 * `empty` - A callback that is called when the last item from the `queue` is given to a `worker`.
1185 * `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`.
1190 // create a cargo object with payload 2
1192 var cargo = async.cargo(function (tasks, callback) {
1193 for(var i=0; i<tasks.length; i++){
1194 console.log('hello ' + tasks[i].name);
1202 cargo.push({name: 'foo'}, function (err) {
1203 console.log('finished processing foo');
1205 cargo.push({name: 'bar'}, function (err) {
1206 console.log('finished processing bar');
1208 cargo.push({name: 'baz'}, function (err) {
1209 console.log('finished processing baz');
1213 ---------------------------------------
1216 ### auto(tasks, [callback])
1218 Determines the best order for running the functions in `tasks`, based on their
1219 requirements. Each function can optionally depend on other functions being completed
1220 first, and each function is run as soon as its requirements are satisfied.
1222 If any of the functions pass an error to their callback, it will not
1223 complete (so any other functions depending on it will not run), and the main
1224 `callback` is immediately called with the error. Functions also receive an
1225 object containing the results of functions which have completed so far.
1227 Note, all functions are called with a `results` object as a second argument,
1228 so it is unsafe to pass functions in the `tasks` object which cannot handle the
1231 For example, this snippet of code:
1235 readData: async.apply(fs.readFile, 'data.txt', 'utf-8')
1239 will have the effect of calling `readFile` with the results object as the last
1240 argument, which will fail:
1243 fs.readFile('data.txt', 'utf-8', cb, {});
1246 Instead, wrap the call to `readFile` in a function which does not forward the
1251 readData: function(cb, results){
1252 fs.readFile('data.txt', 'utf-8', cb);
1259 * `tasks` - An object. Each of its properties is either a function or an array of
1260 requirements, with the function itself the last item in the array. The object's key
1261 of a property serves as the name of the task defined by that property,
1262 i.e. can be used when specifying requirements for other tasks.
1263 The function receives two arguments: (1) a `callback(err, result)` which must be
1264 called when finished, passing an `error` (which can be `null`) and the result of
1265 the function's execution, and (2) a `results` object, containing the results of
1266 the previously executed functions.
1267 * `callback(err, results)` - An optional callback which is called when all the
1268 tasks have been completed. It receives the `err` argument if any `tasks`
1269 pass an error to their callback. Results are always returned; however, if
1270 an error occurs, no further `tasks` will be performed, and the results
1271 object will only contain partial results.
1278 get_data: function(callback){
1279 console.log('in get_data');
1280 // async code to get some data
1281 callback(null, 'data', 'converted to array');
1283 make_folder: function(callback){
1284 console.log('in make_folder');
1285 // async code to create a directory to store a file in
1286 // this is run at the same time as getting the data
1287 callback(null, 'folder');
1289 write_file: ['get_data', 'make_folder', function(callback, results){
1290 console.log('in write_file', JSON.stringify(results));
1291 // once there is some data and the directory exists,
1292 // write the data to a file in the directory
1293 callback(null, 'filename');
1295 email_link: ['write_file', function(callback, results){
1296 console.log('in email_link', JSON.stringify(results));
1297 // once the file is written let's email a link to it...
1298 // results.write_file contains the filename returned by write_file.
1299 callback(null, {'file':results.write_file, 'email':'user@example.com'});
1301 }, function(err, results) {
1302 console.log('err = ', err);
1303 console.log('results = ', results);
1307 This is a fairly trivial example, but to do this using the basic parallel and
1308 series functions would look like this:
1313 console.log('in get_data');
1314 // async code to get some data
1315 callback(null, 'data', 'converted to array');
1318 console.log('in make_folder');
1319 // async code to create a directory to store a file in
1320 // this is run at the same time as getting the data
1321 callback(null, 'folder');
1324 function(err, results){
1327 console.log('in write_file', JSON.stringify(results));
1328 // once there is some data and the directory exists,
1329 // write the data to a file in the directory
1330 results.push('filename');
1334 console.log('in email_link', JSON.stringify(results));
1335 // once the file is written let's email a link to it...
1336 callback(null, {'file':results.pop(), 'email':'user@example.com'});
1342 For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding
1343 new tasks much easier (and the code more readable).
1346 ---------------------------------------
1349 ### retry([times = 5], task, [callback])
1351 Attempts to get a successful response from `task` no more than `times` times before
1352 returning an error. If the task is successful, the `callback` will be passed the result
1353 of the successful task. If all attempts fail, the callback will be passed the error and
1354 result (if any) of the final attempt.
1358 * `times` - An integer indicating how many times to attempt the `task` before giving up. Defaults to 5.
1359 * `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)`
1360 which must be called when finished, passing `err` (which can be `null`) and the `result` of
1361 the function's execution, and (2) a `results` object, containing the results of
1362 the previously executed functions (if nested inside another control flow).
1363 * `callback(err, results)` - An optional callback which is called when the
1364 task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`.
1366 The [`retry`](#retry) function can be used as a stand-alone control flow by passing a
1367 callback, as shown below:
1370 async.retry(3, apiMethod, function(err, result) {
1371 // do something with the result
1375 It can also be embeded within other control flow functions to retry individual methods
1376 that are not as reliable, like this:
1380 users: api.getUsers.bind(api),
1381 payments: async.retry(3, api.getPayments.bind(api))
1382 }, function(err, results) {
1383 // do something with the results
1388 ---------------------------------------
1390 <a name="iterator" />
1393 Creates an iterator function which calls the next function in the `tasks` array,
1394 returning a continuation to call the next one after that. It's also possible to
1395 “peek” at the next iterator with `iterator.next()`.
1397 This function is used internally by the `async` module, but can be useful when
1398 you want to manually control the flow of functions in series.
1402 * `tasks` - An array of functions to run.
1407 var iterator = async.iterator([
1408 function(){ sys.p('one'); },
1409 function(){ sys.p('two'); },
1410 function(){ sys.p('three'); }
1413 node> var iterator2 = iterator();
1415 node> var iterator3 = iterator2();
1419 node> var nextfn = iterator2.next();
1424 ---------------------------------------
1427 ### apply(function, arguments..)
1429 Creates a continuation function with some arguments already applied.
1431 Useful as a shorthand when combined with other control flow functions. Any arguments
1432 passed to the returned function are added to the arguments originally passed
1437 * `function` - The function you want to eventually apply all arguments to.
1438 * `arguments...` - Any number of arguments to automatically apply when the
1439 continuation is called.
1447 async.apply(fs.writeFile, 'testfile1', 'test1'),
1448 async.apply(fs.writeFile, 'testfile2', 'test2'),
1452 // the same process without using apply
1456 fs.writeFile('testfile1', 'test1', callback);
1459 fs.writeFile('testfile2', 'test2', callback);
1464 It's possible to pass any number of additional arguments when calling the
1468 node> var fn = async.apply(sys.puts, 'one');
1469 node> fn('two', 'three');
1475 ---------------------------------------
1477 <a name="nextTick" />
1478 ### nextTick(callback), setImmediate(callback)
1480 Calls `callback` on a later loop around the event loop. In Node.js this just
1481 calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)`
1482 if available, otherwise `setTimeout(callback, 0)`, which means other higher priority
1483 events may precede the execution of `callback`.
1485 This is used internally for browser-compatibility purposes.
1489 * `callback` - The function to call on a later loop around the event loop.
1494 var call_order = [];
1495 async.nextTick(function(){
1496 call_order.push('two');
1497 // call_order now equals ['one','two']
1499 call_order.push('one')
1503 ### times(n, callback)
1505 Calls the `callback` function `n` times, and accumulates results in the same manner
1506 you would use with [`map`](#map).
1510 * `n` - The number of times to run the function.
1511 * `callback` - The function to call `n` times.
1516 // Pretend this is some complicated async factory
1517 var createUser = function(id, callback) {
1523 async.times(5, function(n, next){
1524 createUser(n, function(err, user) {
1527 }, function(err, users) {
1528 // we should now have 5 users
1532 <a name="timesSeries" />
1533 ### timesSeries(n, callback)
1535 The same as [`times`](#times), only the iterator is applied to each item in `arr` in
1536 series. The next `iterator` is only called once the current one has completed.
1537 The results array will be in the same order as the original.
1542 <a name="memoize" />
1543 ### memoize(fn, [hasher])
1545 Caches the results of an `async` function. When creating a hash to store function
1546 results against, the callback is omitted from the hash and an optional hash
1547 function can be used.
1549 The cache of results is exposed as the `memo` property of the function returned
1554 * `fn` - The function to proxy and cache results from.
1555 * `hasher` - Tn optional function for generating a custom hash for storing
1556 results. It has all the arguments applied to it apart from the callback, and
1557 must be synchronous.
1562 var slow_fn = function (name, callback) {
1564 callback(null, result);
1566 var fn = async.memoize(slow_fn);
1568 // fn can now be used as if it were slow_fn
1569 fn('some name', function () {
1574 <a name="unmemoize" />
1577 Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized
1578 form. Handy for testing.
1582 * `fn` - the memoized function
1585 ### log(function, arguments)
1587 Logs the result of an `async` function to the `console`. Only works in Node.js or
1588 in browsers that support `console.log` and `console.error` (such as FF and Chrome).
1589 If multiple arguments are returned from the async function, `console.log` is
1590 called on each argument in order.
1594 * `function` - The function you want to eventually apply all arguments to.
1595 * `arguments...` - Any number of arguments to apply to the function.
1600 var hello = function(name, callback){
1601 setTimeout(function(){
1602 callback(null, 'hello ' + name);
1607 node> async.log(hello, 'world');
1611 ---------------------------------------
1614 ### dir(function, arguments)
1616 Logs the result of an `async` function to the `console` using `console.dir` to
1617 display the properties of the resulting object. Only works in Node.js or
1618 in browsers that support `console.dir` and `console.error` (such as FF and Chrome).
1619 If multiple arguments are returned from the async function, `console.dir` is
1620 called on each argument in order.
1624 * `function` - The function you want to eventually apply all arguments to.
1625 * `arguments...` - Any number of arguments to apply to the function.
1630 var hello = function(name, callback){
1631 setTimeout(function(){
1632 callback(null, {hello: name});
1637 node> async.dir(hello, 'world');
1641 ---------------------------------------
1643 <a name="noConflict" />
1646 Changes the value of `async` back to its original value, returning a reference to the