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 control flow (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)
99 * [unmemoize](#unmemoize)
102 * [noConflict](#noConflict)
108 ### forEach(arr, iterator, callback)
110 Applies an iterator function to each item in an array, in parallel.
111 The iterator is called with an item from the list and a callback for when it
112 has finished. If the iterator passes an error to this callback, the main
113 callback for the forEach function is immediately called with the error.
115 Note, that since this function applies the iterator to each item in parallel
116 there is no guarantee that the iterator functions will complete in order.
120 * arr - An array to iterate over.
121 * iterator(item, callback) - A function to apply to each item in the array.
122 The iterator is passed a callback which must be called once it has completed.
123 * callback(err) - A callback which is called after all the iterator functions
124 have finished, or an error has occurred.
128 // assuming openFiles is an array of file names and saveFile is a function
129 // to save the modified contents of that file:
131 async.forEach(openFiles, saveFile, function(err){
132 // if any of the saves produced an error, err would equal that error
135 ---------------------------------------
137 <a name="forEachSeries" />
138 ### forEachSeries(arr, iterator, callback)
140 The same as forEach only the iterator is applied to each item in the array in
141 series. The next iterator is only called once the current one has completed
142 processing. This means the iterator functions will complete in order.
145 ---------------------------------------
147 <a name="forEachLimit" />
148 ### forEachLimit(arr, limit, iterator, callback)
150 The same as forEach only the iterator is applied to batches of items in the
151 array, in series. The next batch of iterators is only called once the current
152 one has completed processing.
156 * arr - An array to iterate over.
157 * limit - How many items should be in each batch.
158 * iterator(item, callback) - A function to apply to each item in the array.
159 The iterator is passed a callback which must be called once it has completed.
160 * callback(err) - A callback which is called after all the iterator functions
161 have finished, or an error has occurred.
165 // Assume documents is an array of JSON objects and requestApi is a
166 // function that interacts with a rate-limited REST api.
168 async.forEachLimit(documents, 20, requestApi, function(err){
169 // if any of the saves produced an error, err would equal that error
171 ---------------------------------------
174 ### map(arr, iterator, callback)
176 Produces a new array of values by mapping each value in the given array through
177 the iterator function. The iterator is called with an item from the array and a
178 callback for when it has finished processing. The callback takes 2 arguments,
179 an error and the transformed item from the array. If the iterator passes an
180 error to this callback, the main callback for the map function is immediately
181 called with the error.
183 Note, that since this function applies the iterator to each item in parallel
184 there is no guarantee that the iterator functions will complete in order, however
185 the results array will be in the same order as the original array.
189 * arr - An array to iterate over.
190 * iterator(item, callback) - A function to apply to each item in the array.
191 The iterator is passed a callback which must be called once it has completed
192 with an error (which can be null) and a transformed item.
193 * callback(err, results) - A callback which is called after all the iterator
194 functions have finished, or an error has occurred. Results is an array of the
195 transformed items from the original array.
199 async.map(['file1','file2','file3'], fs.stat, function(err, results){
200 // results is now an array of stats for each file
203 ---------------------------------------
205 <a name="mapSeries" />
206 ### mapSeries(arr, iterator, callback)
208 The same as map only the iterator is applied to each item in the array in
209 series. The next iterator is only called once the current one has completed
210 processing. The results array will be in the same order as the original.
213 ---------------------------------------
216 ### filter(arr, iterator, callback)
220 Returns a new array of all the values which pass an async truth test.
221 _The callback for each iterator call only accepts a single argument of true or
222 false, it does not accept an error argument first!_ This is in-line with the
223 way node libraries work with truth tests like path.exists. This operation is
224 performed in parallel, but the results array will be in the same order as the
229 * arr - An array to iterate over.
230 * iterator(item, callback) - A truth test to apply to each item in the array.
231 The iterator is passed a callback which must be called once it has completed.
232 * callback(results) - A callback which is called after all the iterator
233 functions have finished.
237 async.filter(['file1','file2','file3'], path.exists, function(results){
238 // results now equals an array of the existing files
241 ---------------------------------------
243 <a name="filterSeries" />
244 ### filterSeries(arr, iterator, callback)
246 __alias:__ selectSeries
248 The same as filter only the iterator is applied to each item in the array in
249 series. The next iterator is only called once the current one has completed
250 processing. The results array will be in the same order as the original.
252 ---------------------------------------
255 ### reject(arr, iterator, callback)
257 The opposite of filter. Removes values that pass an async truth test.
259 ---------------------------------------
261 <a name="rejectSeries" />
262 ### rejectSeries(arr, iterator, callback)
264 The same as filter, only the iterator is applied to each item in the array
268 ---------------------------------------
271 ### reduce(arr, memo, iterator, callback)
273 __aliases:__ inject, foldl
275 Reduces a list of values into a single value using an async iterator to return
276 each successive step. Memo is the initial state of the reduction. This
277 function only operates in series. For performance reasons, it may make sense to
278 split a call to this function into a parallel map, then use the normal
279 Array.prototype.reduce on the results. This function is for situations where
280 each step in the reduction needs to be async, if you can get the data before
281 reducing it then its probably a good idea to do so.
285 * arr - An array to iterate over.
286 * memo - The initial state of the reduction.
287 * iterator(memo, item, callback) - A function applied to each item in the
288 array to produce the next step in the reduction. The iterator is passed a
289 callback which accepts an optional error as its first argument, and the state
290 of the reduction as the second. If an error is passed to the callback, the
291 reduction is stopped and the main callback is immediately called with the
293 * callback(err, result) - A callback which is called after all the iterator
294 functions have finished. Result is the reduced value.
298 async.reduce([1,2,3], 0, function(memo, item, callback){
300 process.nextTick(function(){
301 callback(null, memo + item)
303 }, function(err, result){
304 // result is now equal to the last value of memo, which is 6
307 ---------------------------------------
309 <a name="reduceRight" />
310 ### reduceRight(arr, memo, iterator, callback)
314 Same as reduce, only operates on the items in the array in reverse order.
317 ---------------------------------------
320 ### detect(arr, iterator, callback)
322 Returns the first value in a list that passes an async truth test. The
323 iterator is applied in parallel, meaning the first iterator to return true will
324 fire the detect callback with that result. That means the result might not be
325 the first item in the original array (in terms of order) that passes the test.
327 If order within the original array is important then look at detectSeries.
331 * arr - An array to iterate over.
332 * iterator(item, callback) - A truth test to apply to each item in the array.
333 The iterator is passed a callback which must be called once it has completed.
334 * callback(result) - A callback which is called as soon as any iterator returns
335 true, or after all the iterator functions have finished. Result will be
336 the first item in the array that passes the truth test (iterator) or the
337 value undefined if none passed.
341 async.detect(['file1','file2','file3'], path.exists, function(result){
342 // result now equals the first file in the list that exists
345 ---------------------------------------
347 <a name="detectSeries" />
348 ### detectSeries(arr, iterator, callback)
350 The same as detect, only the iterator is applied to each item in the array
351 in series. This means the result is always the first in the original array (in
352 terms of array order) that passes the truth test.
355 ---------------------------------------
358 ### sortBy(arr, iterator, callback)
360 Sorts a list by the results of running each value through an async iterator.
364 * arr - An array to iterate over.
365 * iterator(item, callback) - A function to apply to each item in the array.
366 The iterator is passed a callback which must be called once it has completed
367 with an error (which can be null) and a value to use as the sort criteria.
368 * callback(err, results) - A callback which is called after all the iterator
369 functions have finished, or an error has occurred. Results is the items from
370 the original array sorted by the values returned by the iterator calls.
374 async.sortBy(['file1','file2','file3'], function(file, callback){
375 fs.stat(file, function(err, stats){
376 callback(err, stats.mtime);
378 }, function(err, results){
379 // results is now the original array of files sorted by
384 ---------------------------------------
387 ### some(arr, iterator, callback)
391 Returns true if at least one element in the array satisfies an async test.
392 _The callback for each iterator call only accepts a single argument of true or
393 false, it does not accept an error argument first!_ This is in-line with the
394 way node libraries work with truth tests like path.exists. Once any iterator
395 call returns true, the main callback is immediately called.
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 as soon as any iterator returns
403 true, or after all the iterator functions have finished. Result will be
404 either true or false depending on the values of the async tests.
408 async.some(['file1','file2','file3'], path.exists, function(result){
409 // if result is true then at least one of the files exists
412 ---------------------------------------
415 ### every(arr, iterator, callback)
419 Returns true if every element in the array satisfies an async test.
420 _The callback for each iterator call only accepts a single argument of true or
421 false, it does not accept an error argument first!_ This is in-line with the
422 way node libraries work with truth tests like path.exists.
426 * arr - An array to iterate over.
427 * iterator(item, callback) - A truth test to apply to each item in the array.
428 The iterator is passed a callback which must be called once it has completed.
429 * callback(result) - A callback which is called after all the iterator
430 functions have finished. Result will be either true or false depending on
431 the values of the async tests.
435 async.every(['file1','file2','file3'], path.exists, function(result){
436 // if result is true then every file exists
439 ---------------------------------------
442 ### concat(arr, iterator, callback)
444 Applies an iterator to each item in a list, concatenating the results. Returns the
445 concatenated list. The iterators are called in parallel, and the results are
446 concatenated as they return. There is no guarantee that the results array will
447 be returned in the original order of the arguments passed to the iterator function.
451 * arr - An array to iterate over
452 * iterator(item, callback) - A function to apply to each item in the array.
453 The iterator is passed a callback which must be called once it has completed
454 with an error (which can be null) and an array of results.
455 * callback(err, results) - A callback which is called after all the iterator
456 functions have finished, or an error has occurred. Results is an array containing
457 the concatenated results of the iterator function.
461 async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
462 // files is now a list of filenames that exist in the 3 directories
465 ---------------------------------------
467 <a name="concatSeries" />
468 ### concatSeries(arr, iterator, callback)
470 Same as async.concat, but executes in series instead of parallel.
476 ### series(tasks, [callback])
478 Run an array of functions in series, each one running once the previous
479 function has completed. If any functions in the series pass an error to its
480 callback, no more functions are run and the callback for the series is
481 immediately called with the value of the error. Once the tasks have completed,
482 the results are passed to the final callback as an array.
484 It is also possible to use an object instead of an array. Each property will be
485 run as a function and the results will be passed to the final callback as an object
486 instead of an array. This can be a more readable way of handling results from
492 * tasks - An array or object containing functions to run, each function is passed
493 a callback it must call on completion.
494 * callback(err, results) - An optional callback to run once all the functions
495 have completed. This function gets an array of all the arguments passed to
496 the callbacks used in the array.
503 callback(null, 'one');
506 // do some more stuff ...
507 callback(null, 'two');
511 function(err, results){
512 // results is now equal to ['one', 'two']
516 // an example using an object instead of an array
518 one: function(callback){
519 setTimeout(function(){
523 two: function(callback){
524 setTimeout(function(){
529 function(err, results) {
530 // results is now equal to: {one: 1, two: 2}
534 ---------------------------------------
536 <a name="parallel" />
537 ### parallel(tasks, [callback])
539 Run an array of functions in parallel, without waiting until the previous
540 function has completed. If any of the functions pass an error to its
541 callback, the main callback is immediately called with the value of the error.
542 Once the tasks have completed, the results are passed to the final callback as an
545 It is also possible to use an object instead of an array. Each property will be
546 run as a function and the results will be passed to the final callback as an object
547 instead of an array. This can be a more readable way of handling results from
553 * tasks - An array or object containing functions to run, each function is passed a
554 callback it must call on completion.
555 * callback(err, results) - An optional callback to run once all the functions
556 have completed. This function gets an array of all the arguments passed to
557 the callbacks used in the array.
563 setTimeout(function(){
564 callback(null, 'one');
568 setTimeout(function(){
569 callback(null, 'two');
574 function(err, results){
575 // the results array will equal ['one','two'] even though
576 // the second function had a shorter timeout.
580 // an example using an object instead of an array
582 one: function(callback){
583 setTimeout(function(){
587 two: function(callback){
588 setTimeout(function(){
593 function(err, results) {
594 // results is now equals to: {one: 1, two: 2}
598 ---------------------------------------
601 ### whilst(test, fn, callback)
603 Repeatedly call fn, while test returns true. Calls the callback when stopped,
608 * test() - synchronous truth test to perform before each execution of fn.
609 * fn(callback) - A function to call each time the test passes. The function is
610 passed a callback which must be called once it has completed with an optional
611 error as the first argument.
612 * callback(err) - A callback which is called after the test fails and repeated
613 execution of fn has stopped.
620 function () { return count < 5; },
621 function (callback) {
623 setTimeout(callback, 1000);
626 // 5 seconds have passed
631 ---------------------------------------
634 ### until(test, fn, callback)
636 Repeatedly call fn, until test returns true. Calls the callback when stopped,
639 The inverse of async.whilst.
642 ---------------------------------------
644 <a name="waterfall" />
645 ### waterfall(tasks, [callback])
647 Runs an array of functions in series, each passing their results to the next in
648 the array. However, if any of the functions pass an error to the callback, the
649 next function is not executed and the main callback is immediately called with
654 * tasks - An array of functions to run, each function is passed a callback it
655 must call on completion.
656 * callback(err, [results]) - An optional callback to run once all the functions
657 have completed. This will be passed the results of the last task's callback.
665 callback(null, 'one', 'two');
667 function(arg1, arg2, callback){
668 callback(null, 'three');
670 function(arg1, callback){
671 // arg1 now equals 'three'
672 callback(null, 'done');
674 ], function (err, result) {
675 // result now equals 'done'
679 ---------------------------------------
682 ### queue(worker, concurrency)
684 Creates a queue object with the specified concurrency. Tasks added to the
685 queue will be processed in parallel (up to the concurrency limit). If all
686 workers are in progress, the task is queued until one is available. Once
687 a worker has completed a task, the task's callback is called.
691 * worker(task, callback) - An asynchronous function for processing a queued
693 * concurrency - An integer for determining how many worker functions should be
698 The queue object returned by this function has the following properties and
701 * length() - a function returning the number of items waiting to be processed.
702 * concurrency - an integer for determining how many worker functions should be
703 run in parallel. This property can be changed after a queue is created to
704 alter the concurrency on-the-fly.
705 * push(task, [callback]) - add a new task to the queue, the callback is called
706 once the worker has finished processing the task.
707 instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list.
708 * saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued
709 * empty - a callback that is called when the last item from the queue is given to a worker
710 * drain - a callback that is called when the last item from the queue has returned from the worker
714 // create a queue object with concurrency 2
716 var q = async.queue(function (task, callback) {
717 console.log('hello ' + task.name);
723 q.drain = function() {
724 console.log('all items have been processed');
727 // add some items to the queue
729 q.push({name: 'foo'}, function (err) {
730 console.log('finished processing foo');
732 q.push({name: 'bar'}, function (err) {
733 console.log('finished processing bar');
736 // add some items to the queue (batch-wise)
738 q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {
739 console.log('finished processing bar');
743 ---------------------------------------
746 ### auto(tasks, [callback])
748 Determines the best order for running functions based on their requirements.
749 Each function can optionally depend on other functions being completed first,
750 and each function is run as soon as its requirements are satisfied. If any of
751 the functions pass an error to their callback, that function will not complete
752 (so any other functions depending on it will not run) and the main callback
753 will be called immediately with the error. Functions also receive an object
754 containing the results of functions which have completed so far.
758 * tasks - An object literal containing named functions or an array of
759 requirements, with the function itself the last item in the array. The key
760 used for each function or array is used when specifying requirements. The
761 syntax is easier to understand by looking at the example.
762 * callback(err, results) - An optional callback which is called when all the
763 tasks have been completed. The callback will receive an error as an argument
764 if any tasks pass an error to their callback. If all tasks complete
765 successfully, it will receive an object containing their results.
770 get_data: function(callback){
771 // async code to get some data
773 make_folder: function(callback){
774 // async code to create a directory to store a file in
775 // this is run at the same time as getting the data
777 write_file: ['get_data', 'make_folder', function(callback){
778 // once there is some data and the directory exists,
779 // write the data to a file in the directory
780 callback(null, filename);
782 email_link: ['write_file', function(callback, results){
783 // once the file is written let's email a link to it...
784 // results.write_file contains the filename returned by write_file.
788 This is a fairly trivial example, but to do this using the basic parallel and
789 series functions would look like this:
793 // async code to get some data
796 // async code to create a directory to store a file in
797 // this is run at the same time as getting the data
803 // once there is some data and the directory exists,
804 // write the data to a file in the directory
806 email_link: function(callback){
807 // once the file is written let's email a link to it...
812 For a complicated series of async tasks using the auto function makes adding
813 new tasks much easier and makes the code more readable.
816 ---------------------------------------
818 <a name="iterator" />
821 Creates an iterator function which calls the next function in the array,
822 returning a continuation to call the next one after that. Its also possible to
823 'peek' the next iterator by doing iterator.next().
825 This function is used internally by the async module but can be useful when
826 you want to manually control the flow of functions in series.
830 * tasks - An array of functions to run, each function is passed a callback it
831 must call on completion.
835 var iterator = async.iterator([
836 function(){ sys.p('one'); },
837 function(){ sys.p('two'); },
838 function(){ sys.p('three'); }
841 node> var iterator2 = iterator();
843 node> var iterator3 = iterator2();
847 node> var nextfn = iterator2.next();
852 ---------------------------------------
855 ### apply(function, arguments..)
857 Creates a continuation function with some arguments already applied, a useful
858 shorthand when combined with other control flow functions. Any arguments
859 passed to the returned function are added to the arguments originally passed
864 * function - The function you want to eventually apply all arguments to.
865 * arguments... - Any number of arguments to automatically apply when the
866 continuation is called.
873 async.apply(fs.writeFile, 'testfile1', 'test1'),
874 async.apply(fs.writeFile, 'testfile2', 'test2'),
878 // the same process without using apply
882 fs.writeFile('testfile1', 'test1', callback);
885 fs.writeFile('testfile2', 'test2', callback);
889 It's possible to pass any number of additional arguments when calling the
892 node> var fn = async.apply(sys.puts, 'one');
893 node> fn('two', 'three');
898 ---------------------------------------
900 <a name="nextTick" />
901 ### nextTick(callback)
903 Calls the callback on a later loop around the event loop. In node.js this just
904 calls process.nextTick, in the browser it falls back to setTimeout(callback, 0),
905 which means other higher priority events may precede the execution of the callback.
907 This is used internally for browser-compatibility purposes.
911 * callback - The function to call on a later loop around the event loop.
916 async.nextTick(function(){
917 call_order.push('two');
918 // call_order now equals ['one','two]
920 call_order.push('one')
926 ### memoize(fn, [hasher])
928 Caches the results of an async function. When creating a hash to store function
929 results against, the callback is omitted from the hash and an optional hash
930 function can be used.
934 * fn - the function you to proxy and cache results from.
935 * hasher - an optional function for generating a custom hash for storing
936 results, it has all the arguments applied to it apart from the callback, and
941 var slow_fn = function (name, callback) {
943 callback(null, result);
945 var fn = async.memoize(slow_fn);
947 // fn can now be used as if it were slow_fn
948 fn('some name', function () {
952 <a name="unmemoize" />
955 Undoes a memoized function, reverting it to the original, unmemoized
956 form. Comes handy in tests.
960 * fn - the memoized function
963 ### log(function, arguments)
965 Logs the result of an async function to the console. Only works in node.js or
966 in browsers that support console.log and console.error (such as FF and Chrome).
967 If multiple arguments are returned from the async function, console.log is
968 called on each argument in order.
972 * function - The function you want to eventually apply all arguments to.
973 * arguments... - Any number of arguments to apply to the function.
977 var hello = function(name, callback){
978 setTimeout(function(){
979 callback(null, 'hello ' + name);
983 node> async.log(hello, 'world');
987 ---------------------------------------
990 ### dir(function, arguments)
992 Logs the result of an async function to the console using console.dir to
993 display the properties of the resulting object. Only works in node.js or
994 in browsers that support console.dir and console.error (such as FF and Chrome).
995 If multiple arguments are returned from the async function, console.dir is
996 called on each argument in order.
1000 * function - The function you want to eventually apply all arguments to.
1001 * arguments... - Any number of arguments to apply to the function.
1005 var hello = function(name, callback){
1006 setTimeout(function(){
1007 callback(null, {hello: name});
1011 node> async.dir(hello, 'world');
1015 ---------------------------------------
1017 <a name="noConflict" />
1020 Changes the value of async back to its original value, returning a reference to the