3 Async is a utility module which provides straight-forward, powerful functions
4 for working with asynchronous JavaScript. Although originally designed for
5 use with [node.js](http://nodejs.org), it can also be used directly in the
8 Async provides around 20 functions that include the usual 'functional'
9 suspects (map, reduce, filter, forEach…) as well as some common patterns
10 for asynchronous flow control (parallel, series, waterfall…). All these
11 functions assume you follow the node.js convention of providing a single
12 callback as the last argument of your async function.
17 async.map(['file1','file2','file3'], fs.stat, function(err, results){
18 // results is now an array of stats for each file
21 async.filter(['file1','file2','file3'], path.exists, function(results){
22 // results now equals an array of the existing files
35 There are many more functions available so take a look at the docs below for a
36 full list. This module aims to be comprehensive, so if you feel anything is
37 missing please create a GitHub issue for it.
42 Releases are available for download from
43 [GitHub](http://github.com/caolan/async/downloads).
44 Alternatively, you can install using Node Package Manager (npm):
49 __Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 17.5kb Uncompressed
51 __Production:__ [async.min.js](https://github.com/caolan/async/raw/master/dist/async.min.js) - 1.7kb Packed and Gzipped
56 So far its been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. Usage:
58 <script type="text/javascript" src="async.js"></script>
59 <script type="text/javascript">
61 async.map(data, asyncProcess, function(err, results){
86 * [parallel](#parallel)
89 * [waterfall](#waterfall)
92 * [iterator](#iterator)
94 * [nextTick](#nextTick)
101 * [noConflict](#noConflict)
107 ### forEach(arr, iterator, callback)
109 Applies an iterator function to each item in an array, in parallel.
110 The iterator is called with an item from the list and a callback for when it
111 has finished. If the iterator passes an error to this callback, the main
112 callback for the forEach function is immediately called with the error.
114 Note, that since this function applies the iterator to each item in parallel
115 there is no guarantee that the iterator functions will complete in order.
119 * arr - An array to iterate over.
120 * iterator(item, callback) - A function to apply to each item in the array.
121 The iterator is passed a callback which must be called once it has completed.
122 * callback(err) - A callback which is called after all the iterator functions
123 have finished, or an error has occurred.
127 // assuming openFiles is an array of file names and saveFile is a function
128 // to save the modified contents of that file:
130 async.forEach(openFiles, saveFile, function(err){
131 // if any of the saves produced an error, err would equal that error
134 ---------------------------------------
136 <a name="forEachSeries" />
137 ### forEachSeries(arr, iterator, callback)
139 The same as forEach only the iterator is applied to each item in the array in
140 series. The next iterator is only called once the current one has completed
141 processing. This means the iterator functions will complete in order.
144 ---------------------------------------
147 ### map(arr, iterator, callback)
149 Produces a new array of values by mapping each value in the given array through
150 the iterator function. The iterator is called with an item from the array and a
151 callback for when it has finished processing. The callback takes 2 arguments,
152 an error and the transformed item from the array. If the iterator passes an
153 error to this callback, the main callback for the map function is immediately
154 called with the error.
156 Note, that since this function applies the iterator to each item in parallel
157 there is no guarantee that the iterator functions will complete in order, however
158 the results array will be in the same order as the original array.
162 * arr - An array to iterate over.
163 * iterator(item, callback) - A function to apply to each item in the array.
164 The iterator is passed a callback which must be called once it has completed
165 with an error (which can be null) and a transformed item.
166 * callback(err, results) - A callback which is called after all the iterator
167 functions have finished, or an error has occurred. Results is an array of the
168 transformed items from the original array.
172 async.map(['file1','file2','file3'], fs.stat, function(err, results){
173 // results is now an array of stats for each file
176 ---------------------------------------
178 <a name="mapSeries" />
179 ### mapSeries(arr, iterator, callback)
181 The same as map only the iterator is applied to each item in the array in
182 series. The next iterator is only called once the current one has completed
183 processing. The results array will be in the same order as the original.
186 ---------------------------------------
189 ### filter(arr, iterator, callback)
193 Returns a new array of all the values which pass an async truth test.
194 _The callback for each iterator call only accepts a single argument of true or
195 false, it does not accept an error argument first!_ This is in-line with the
196 way node libraries work with truth tests like path.exists. This operation is
197 performed in parallel, but the results array will be in the same order as the
202 * arr - An array to iterate over.
203 * iterator(item, callback) - A truth test to apply to each item in the array.
204 The iterator is passed a callback which must be called once it has completed.
205 * callback(results) - A callback which is called after all the iterator
206 functions have finished.
210 async.filter(['file1','file2','file3'], path.exists, function(results){
211 // results now equals an array of the existing files
214 ---------------------------------------
216 <a name="filterSeries" />
217 ### filterSeries(arr, iterator, callback)
219 __alias:__ selectSeries
221 The same as filter only the iterator is applied to each item in the array in
222 series. The next iterator is only called once the current one has completed
223 processing. The results array will be in the same order as the original.
225 ---------------------------------------
228 ### reject(arr, iterator, callback)
230 The opposite of filter. Removes values that pass an async truth test.
232 ---------------------------------------
234 <a name="rejectSeries" />
235 ### rejectSeries(arr, iterator, callback)
237 The same as filter, only the iterator is applied to each item in the array
241 ---------------------------------------
244 ### reduce(arr, memo, iterator, callback)
246 __aliases:__ inject, foldl
248 Reduces a list of values into a single value using an async iterator to return
249 each successive step. Memo is the initial state of the reduction. This
250 function only operates in series. For performance reasons, it may make sense to
251 split a call to this function into a parallel map, then use the normal
252 Array.prototype.reduce on the results. This function is for situations where
253 each step in the reduction needs to be async, if you can get the data before
254 reducing it then its probably a good idea to do so.
258 * arr - An array to iterate over.
259 * memo - The initial state of the reduction.
260 * iterator(memo, item, callback) - A function applied to each item in the
261 array to produce the next step in the reduction. The iterator is passed a
262 callback which accepts an optional error as its first argument, and the state
263 of the reduction as the second. If an error is passed to the callback, the
264 reduction is stopped and the main callback is immediately called with the
266 * callback(err, result) - A callback which is called after all the iterator
267 functions have finished. Result is the reduced value.
271 async.reduce([1,2,3], 0, function(memo, item, callback){
273 process.nextTick(function(){
274 callback(null, memo + item)
276 }, function(err, result){
277 // result is now equal to the last value of memo, which is 6
280 ---------------------------------------
282 <a name="reduceRight" />
283 ### reduceRight(arr, memo, iterator, callback)
287 Same as reduce, only operates on the items in the array in reverse order.
290 ---------------------------------------
293 ### detect(arr, iterator, callback)
295 Returns the first value in a list that passes an async truth test. The
296 iterator is applied in parallel, meaning the first iterator to return true will
297 fire the detect callback with that result. That means the result might not be
298 the first item in the original array (in terms of order) that passes the test.
300 If order within the original array is important then look at detectSeries.
304 * arr - An array to iterate over.
305 * iterator(item, callback) - A truth test to apply to each item in the array.
306 The iterator is passed a callback which must be called once it has completed.
307 * callback(result) - A callback which is called as soon as any iterator returns
308 true, or after all the iterator functions have finished. Result will be
309 the first item in the array that passes the truth test (iterator) or the
310 value undefined if none passed.
314 async.detect(['file1','file2','file3'], path.exists, function(result){
315 // result now equals the first file in the list that exists
318 ---------------------------------------
320 <a name="detectSeries" />
321 ### detectSeries(arr, iterator, callback)
323 The same as detect, only the iterator is applied to each item in the array
324 in series. This means the result is always the first in the original array (in
325 terms of array order) that passes the truth test.
328 ---------------------------------------
331 ### sortBy(arr, iterator, callback)
333 Sorts a list by the results of running each value through an async iterator.
337 * arr - An array to iterate over.
338 * iterator(item, callback) - A function to apply to each item in the array.
339 The iterator is passed a callback which must be called once it has completed
340 with an error (which can be null) and a value to use as the sort criteria.
341 * callback(err, results) - A callback which is called after all the iterator
342 functions have finished, or an error has occurred. Results is the items from
343 the original array sorted by the values returned by the iterator calls.
347 async.sortBy(['file1','file2','file3'], function(file, callback){
348 fs.stat(file, function(err, stats){
349 callback(err, stats.mtime);
351 }, function(err, results){
352 // results is now the original array of files sorted by
357 ---------------------------------------
360 ### some(arr, iterator, callback)
364 Returns true if at least one element in the array satisfies an async 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 path.exists. Once any iterator
368 call returns true, the main callback is immediately called.
372 * arr - An array to iterate over.
373 * iterator(item, callback) - A truth test to apply to each item in the array.
374 The iterator is passed a callback which must be called once it has completed.
375 * callback(result) - A callback which is called as soon as any iterator returns
376 true, or after all the iterator functions have finished. Result will be
377 either true or false depending on the values of the async tests.
381 async.some(['file1','file2','file3'], path.exists, function(result){
382 // if result is true then at least one of the files exists
385 ---------------------------------------
388 ### every(arr, iterator, callback)
392 Returns true if every element in the array satisfies an async test.
393 _The callback for each iterator call only accepts a single argument of true or
394 false, it does not accept an error argument first!_ This is in-line with the
395 way node libraries work with truth tests like path.exists.
399 * arr - An array to iterate over.
400 * iterator(item, callback) - A truth test to apply to each item in the array.
401 The iterator is passed a callback which must be called once it has completed.
402 * callback(result) - A callback which is called after all the iterator
403 functions have finished. Result will be either true or false depending on
404 the values of the async tests.
408 async.every(['file1','file2','file3'], path.exists, function(result){
409 // if result is true then every file exists
412 ---------------------------------------
415 ### concat(arr, iterator, callback)
417 Applies an iterator to each item in a list, concatenating the results. Returns the
418 concatenated list. The iterators are called in parallel, and the results are
419 concatenated as they return. There is no guarantee that the results array will
420 be returned in the original order of the arguments passed to the iterator function.
424 * arr - An array to iterate over
425 * iterator(item, callback) - A function to apply to each item in the array.
426 The iterator is passed a callback which must be called once it has completed
427 with an error (which can be null) and an array of results.
428 * callback(err, results) - A callback which is called after all the iterator
429 functions have finished, or an error has occurred. Results is an array containing
430 the concatenated results of the iterator function.
434 async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
435 // files is now a list of filenames that exist in the 3 directories
438 ---------------------------------------
440 <a name="concatSeries" />
441 ### concatSeries(arr, iterator, callback)
443 Same as async.concat, but executes in series instead of parallel.
449 ### series(tasks, [callback])
451 Run an array of functions in series, each one running once the previous
452 function has completed. If any functions in the series pass an error to its
453 callback, no more functions are run and the callback for the series is
454 immediately called with the value of the error. Once the tasks have completed,
455 the results are passed to the final callback as an array.
457 It is also possible to use an object instead of an array. Each property will be
458 run as a function and the results will be passed to the final callback as an object
459 instead of an array. This can be a more readable way of handling results from
465 * tasks - An array or object containing functions to run, each function is passed
466 a callback it must call on completion.
467 * callback(err, results) - An optional callback to run once all the functions
468 have completed. This function gets an array of all the arguments passed to
469 the callbacks used in the array.
476 callback(null, 'one');
479 // do some more stuff ...
480 callback(null, 'two');
484 function(err, results){
485 // results is now equal to ['one', 'two']
489 // an example using an object instead of an array
491 one: function(callback){
492 setTimeout(function(){
496 two: function(callback){
497 setTimeout(function(){
502 function(err, results) {
503 // results is now equals to: {one: 1, two: 2}
507 ---------------------------------------
509 <a name="parallel" />
510 ### parallel(tasks, [callback])
512 Run an array of functions in parallel, without waiting until the previous
513 function has completed. If any of the functions pass an error to its
514 callback, the main callback is immediately called with the value of the error.
515 Once the tasks have completed, the results are passed to the final callback as an
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
526 * tasks - An array or object containing functions to run, each function is passed a
527 callback it must call on completion.
528 * callback(err, results) - An optional callback to run once all the functions
529 have completed. This function gets an array of all the arguments passed to
530 the callbacks used in the array.
536 setTimeout(function(){
537 callback(null, 'one');
541 setTimeout(function(){
542 callback(null, 'two');
547 function(err, results){
548 // in this case, the results array will equal ['two','one']
549 // because the functions were run in parallel and the second
550 // function had a shorter timeout before calling the callback.
554 // an example using an object instead of an array
556 one: function(callback){
557 setTimeout(function(){
561 two: function(callback){
562 setTimeout(function(){
567 function(err, results) {
568 // results is now equals to: {one: 1, two: 2}
572 ---------------------------------------
575 ### whilst(test, fn, callback)
577 Repeatedly call fn, while test returns true. Calls the callback when stopped,
582 * test() - synchronous truth test to perform before each execution of fn.
583 * fn(callback) - A function to call each time the test passes. The function is
584 passed a callback which must be called once it has completed with an optional
585 error as the first argument.
586 * callback(err) - A callback which is called after the test fails and repeated
587 execution of fn has stopped.
594 function () { return count < 5; },
595 function (callback) {
597 setTimeout(callback, 1000);
600 // 5 seconds have passed
605 ---------------------------------------
608 ### until(test, fn, callback)
610 Repeatedly call fn, until test returns true. Calls the callback when stopped,
613 The inverse of async.whilst.
616 ---------------------------------------
618 <a name="waterfall" />
619 ### waterfall(tasks, [callback])
621 Runs an array of functions in series, each passing their results to the next in
622 the array. However, if any of the functions pass an error to the callback, the
623 next function is not executed and the main callback is immediately called with
628 * tasks - An array of functions to run, each function is passed a callback it
629 must call on completion.
630 * callback(err) - An optional callback to run once all the functions have
631 completed. This function gets passed any error that may have occurred.
637 callback(null, 'one', 'two');
639 function(arg1, arg2, callback){
640 callback(null, 'three');
642 function(arg1, callback){
643 // arg1 now equals 'three'
644 callback(null, 'done');
649 ---------------------------------------
652 ### queue(worker, concurrency)
654 Creates a queue object with the specified concurrency. Tasks added to the
655 queue will be processed in parallel (up to the concurrency limit). If all
656 workers are in progress, the task is queued until one is available. Once
657 a worker has completed a task, the task's callback is called.
661 * worker(task, callback) - An asynchronous function for processing a queued
663 * concurrency - An integer for determining how many worker functions should be
668 The queue object returned by this function has the following properties and
671 * length() - a function returning the number of items waiting to be processed.
672 * concurrency - an integer for determining how many worker functions should be
673 run in parallel. This property can be changed after a queue is created to
674 alter the concurrency on-the-fly.
675 * push(task, [callback]) - add a new task to the queue, the callback is called
676 once the worker has finished processing the task.
677 * saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued
678 * empty - a callback that is called when the last item from the queue is given to a worker
679 * drain - a callback that is called when the last item from the queue has returned from the worker
683 // create a queue object with concurrency 2
685 var q = async.queue(function (task, callback) {
686 console.log('hello ' + task.name).
692 q.drain = function() {
693 console.log('all items have been processed');
696 // add some items to the queue
698 q.push({name: 'foo'}, function (err) {
699 console.log('finished processing foo');
701 q.push({name: 'bar'}, function (err) {
702 console.log('finished processing bar');
706 ---------------------------------------
709 ### auto(tasks, [callback])
711 Determines the best order for running functions based on their requirements.
712 Each function can optionally depend on other functions being completed first,
713 and each function is run as soon as its requirements are satisfied. If any of
714 the functions pass and error to their callback, that function will not complete
715 (so any other functions depending on it will not run) and the main callback
716 will be called immediately with the error.
720 * tasks - An object literal containing named functions or an array of
721 requirements, with the function itself the last item in the array. The key
722 used for each function or array is used when specifying requirements. The
723 syntax is easier to understand by looking at the example.
724 * callback(err) - An optional callback which is called when all the tasks have
725 been completed. The callback may receive an error as an argument.
730 get_data: function(callback){
731 // async code to get some data
733 make_folder: function(callback){
734 // async code to create a directory to store a file in
735 // this is run at the same time as getting the data
737 write_file: ['get_data', 'make_folder', function(callback){
738 // once there is some data and the directory exists,
739 // write the data to a file in the directory
741 email_link: ['write_file', function(callback){
742 // once the file is written let's email a link to it...
746 This is a fairly trivial example, but to do this using the basic parallel and
747 series functions would look like this:
751 // async code to get some data
754 // async code to create a directory to store a file in
755 // this is run at the same time as getting the data
761 // once there is some data and the directory exists,
762 // write the data to a file in the directory
764 email_link: ['write_file', function(callback){
765 // once the file is written let's email a link to it...
770 For a complicated series of async tasks using the auto function makes adding
771 new tasks much easier and makes the code more readable.
774 ---------------------------------------
776 <a name="iterator" />
779 Creates an iterator function which calls the next function in the array,
780 returning a continuation to call the next one after that. Its also possible to
781 'peek' the next iterator by doing iterator.next().
783 This function is used internally by the async module but can be useful when
784 you want to manually control the flow of functions in series.
788 * tasks - An array of functions to run, each function is passed a callback it
789 must call on completion.
793 var iterator = async.iterator([
794 function(){ sys.p('one'); },
795 function(){ sys.p('two'); },
796 function(){ sys.p('three'); }
799 node> var iterator2 = iterator();
801 node> var iterator3 = iterator2();
805 node> var nextfn = iterator2.next();
810 ---------------------------------------
813 ### apply(function, arguments..)
815 Creates a continuation function with some arguments already applied, a useful
816 shorthand when combined with other flow control functions. Any arguments
817 passed to the returned function are added to the arguments originally passed
822 * function - The function you want to eventually apply all arguments to.
823 * arguments... - Any number of arguments to automatically apply when the
824 continuation is called.
831 async.apply(fs.writeFile, 'testfile1', 'test1'),
832 async.apply(fs.writeFile, 'testfile2', 'test2'),
836 // the same process without using apply
840 fs.writeFile('testfile1', 'test1', callback);
843 fs.writeFile('testfile2', 'test2', callback);
847 It's possible to pass any number of additional arguments when calling the
850 node> var fn = async.apply(sys.puts, 'one');
851 node> fn('two', 'three');
856 ---------------------------------------
858 <a name="nextTick" />
859 ### nextTick(callback)
861 Calls the callback on a later loop around the event loop. In node.js this just
862 calls process.nextTick, in the browser it falls back to setTimeout(callback, 0),
863 which means other higher priority events may precede the execution of the callback.
865 This is used internally for browser-compatibility purposes.
869 * callback - The function to call on a later loop around the event loop.
874 async.nextTick(function(){
875 call_order.push('two');
876 // call_order now equals ['one','two]
878 call_order.push('one')
884 ### memoize(fn, [hasher])
886 Caches the results of an async function. When creating a hash to store function
887 results against, the callback is omitted from the hash and an optional hash
888 function can be used.
892 * fn - the function you to proxy and cache results from.
893 * hasher - an optional function for generating a custom hash for storing
894 results, it has all the arguments applied to it apart from the callback, and
899 var slow_fn = function (name, callback) {
901 callback(null, result);
903 var fn = async.memoize(slow_fn);
905 // fn can now be used as if it were slow_fn
906 fn('some name', function () {
912 ### log(function, arguments)
914 Logs the result of an async function to the console. Only works in node.js or
915 in browsers that support console.log and console.error (such as FF and Chrome).
916 If multiple arguments are returned from the async function, console.log is
917 called on each argument in order.
921 * function - The function you want to eventually apply all arguments to.
922 * arguments... - Any number of arguments to apply to the function.
926 var hello = function(name, callback){
927 setTimeout(function(){
928 callback(null, 'hello ' + name);
932 node> async.log(hello, 'world');
936 ---------------------------------------
939 ### dir(function, arguments)
941 Logs the result of an async function to the console using console.dir to
942 display the properties of the resulting object. Only works in node.js or
943 in browsers that support console.dir and console.error (such as FF and Chrome).
944 If multiple arguments are returned from the async function, console.dir is
945 called on each argument in order.
949 * function - The function you want to eventually apply all arguments to.
950 * arguments... - Any number of arguments to apply to the function.
954 var hello = function(name, callback){
955 setTimeout(function(){
956 callback(null, {hello: name});
960 node> async.dir(hello, 'world');
964 ---------------------------------------
966 <a name="noConflict" />
969 Changes the value of async back to its original value, returning a reference to the