UNPKG

27.4 kBMarkdownView Raw
1# Async.js
2
3Async is a utility module which provides straight-forward, powerful functions
4for working with asynchronous JavaScript. Although originally designed for
5use with [node.js](http://nodejs.org), it can also be used directly in the
6browser.
7
8Async provides around 20 functions that include the usual 'functional'
9suspects (map, reduce, filter, forEach…) as well as some common patterns
10for asynchronous flow control (parallel, series, waterfall…). All these
11functions assume you follow the node.js convention of providing a single
12callback as the last argument of your async function.
13
14
15## Quick Examples
16
17 async.map(['file1','file2','file3'], fs.stat, function(err, results){
18 // results is now an array of stats for each file
19 });
20
21 async.filter(['file1','file2','file3'], path.exists, function(results){
22 // results now equals an array of the existing files
23 });
24
25 async.parallel([
26 function(){ ... },
27 function(){ ... }
28 ], callback);
29
30 async.series([
31 function(){ ... },
32 function(){ ... }
33 ]);
34
35There are many more functions available so take a look at the docs below for a
36full list. This module aims to be comprehensive, so if you feel anything is
37missing please create a GitHub issue for it.
38
39
40## Download
41
42Releases are available for download from
43[GitHub](http://github.com/caolan/async/downloads).
44Alternatively, you can install using Node Package Manager (npm):
45
46 npm install async
47
48
49## In the Browser
50
51So far its been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. Usage:
52
53 <script type="text/javascript" src="async.js"></script>
54 <script type="text/javascript">
55
56 async.map(data, asyncProcess, function(err, results){
57 alert(results);
58 });
59
60 </script>
61
62
63## Documentation
64
65### Collections
66
67* [forEach](#forEach)
68* [map](#map)
69* [filter](#filter)
70* [reject](#reject)
71* [reduce](#reduce)
72* [detect](#detect)
73* [sortBy](#sortBy)
74* [some](#some)
75* [every](#every)
76* [concat](#concat)
77
78### Flow Control
79
80* [series](#series)
81* [parallel](#parallel)
82* [whilst](#whilst)
83* [until](#until)
84* [waterfall](#waterfall)
85* [auto](#auto)
86* [iterator](#iterator)
87* [apply](#apply)
88* [nextTick](#nextTick)
89
90### Utils
91
92* [log](#log)
93* [dir](#dir)
94* [noConflict](#noConflict)
95
96
97## Collections
98
99<a name="forEach" />
100### forEach(arr, iterator, callback)
101
102Applies an iterator function to each item in an array, in parallel.
103The iterator is called with an item from the list and a callback for when it
104has finished. If the iterator passes an error to this callback, the main
105callback for the forEach function is immediately called with the error.
106
107Note, that since this function applies the iterator to each item in parallel
108there is no guarantee that the iterator functions will complete in order.
109
110__Arguments__
111
112* arr - An array to iterate over.
113* iterator(item, callback) - A function to apply to each item in the array.
114 The iterator is passed a callback which must be called once it has completed.
115* callback(err) - A callback which is called after all the iterator functions
116 have finished, or an error has occurred.
117
118__Example__
119
120 // assuming openFiles is an array of file names and saveFile is a function
121 // to save the modified contents of that file:
122
123 async.forEach(openFiles, saveFile, function(err){
124 // if any of the saves produced an error, err would equal that error
125 });
126
127---------------------------------------
128
129<a name="forEachSeries" />
130### forEachSeries(arr, iterator, callback)
131
132The same as forEach only the iterator is applied to each item in the array in
133series. The next iterator is only called once the current one has completed
134processing. This means the iterator functions will complete in order.
135
136
137---------------------------------------
138
139<a name="map" />
140### map(arr, iterator, callback)
141
142Produces a new array of values by mapping each value in the given array through
143the iterator function. The iterator is called with an item from the array and a
144callback for when it has finished processing. The callback takes 2 arguments,
145an error and the transformed item from the array. If the iterator passes an
146error to this callback, the main callback for the map function is immediately
147called with the error.
148
149Note, that since this function applies the iterator to each item in parallel
150there is no guarantee that the iterator functions will complete in order, however
151the results array will be in the same order as the original array.
152
153__Arguments__
154
155* arr - An array to iterate over.
156* iterator(item, callback) - A function to apply to each item in the array.
157 The iterator is passed a callback which must be called once it has completed
158 with an error (which can be null) and a transformed item.
159* callback(err, results) - A callback which is called after all the iterator
160 functions have finished, or an error has occurred. Results is an array of the
161 transformed items from the original array.
162
163__Example__
164
165 async.map(['file1','file2','file3'], fs.stat, function(err, results){
166 // results is now an array of stats for each file
167 });
168
169---------------------------------------
170
171<a name="mapSeries" />
172### mapSeries(arr, iterator, callback)
173
174The same as map only the iterator is applied to each item in the array in
175series. The next iterator is only called once the current one has completed
176processing. The results array will be in the same order as the original.
177
178
179---------------------------------------
180
181<a name="filter" />
182### filter(arr, iterator, callback)
183
184__Alias:__ select
185
186Returns a new array of all the values which pass an async truth test.
187_The callback for each iterator call only accepts a single argument of true or
188false, it does not accept an error argument first!_ This is in-line with the
189way node libraries work with truth tests like path.exists. This operation is
190performed in parallel, but the results array will be in the same order as the
191original.
192
193__Arguments__
194
195* arr - An array to iterate over.
196* iterator(item, callback) - A truth test to apply to each item in the array.
197 The iterator is passed a callback which must be called once it has completed.
198* callback(results) - A callback which is called after all the iterator
199 functions have finished.
200
201__Example__
202
203 async.filter(['file1','file2','file3'], path.exists, function(results){
204 // results now equals an array of the existing files
205 });
206
207---------------------------------------
208
209<a name="filterSeries" />
210### filterSeries(arr, iterator, callback)
211
212__alias:__ selectSeries
213
214The same as filter only the iterator is applied to each item in the array in
215series. The next iterator is only called once the current one has completed
216processing. The results array will be in the same order as the original.
217
218---------------------------------------
219
220<a name="reject" />
221### reject(arr, iterator, callback)
222
223The opposite of filter. Removes values that pass an async truth test.
224
225---------------------------------------
226
227<a name="rejectSeries" />
228### rejectSeries(arr, iterator, callback)
229
230The same as filter, only the iterator is applied to each item in the array
231in series.
232
233
234---------------------------------------
235
236<a name="reduce" />
237### reduce(arr, memo, iterator, callback)
238
239__aliases:__ inject, foldl
240
241Reduces a list of values into a single value using an async iterator to return
242each successive step. Memo is the initial state of the reduction. This
243function only operates in series. For performance reasons, it may make sense to
244split a call to this function into a parallel map, then use the normal
245Array.prototype.reduce on the results. This function is for situations where
246each step in the reduction needs to be async, if you can get the data before
247reducing it then its probably a good idea to do so.
248
249__Arguments__
250
251* arr - An array to iterate over.
252* memo - The initial state of the reduction.
253* iterator(memo, item, callback) - A function applied to each item in the
254 array to produce the next step in the reduction. The iterator is passed a
255 callback which accepts an optional error as its first argument, and the state
256 of the reduction as the second. If an error is passed to the callback, the
257 reduction is stopped and the main callback is immediately called with the
258 error.
259* callback(err, result) - A callback which is called after all the iterator
260 functions have finished. Result is the reduced value.
261
262__Example__
263
264 async.reduce([1,2,3], 0, function(memo, item, callback){
265 // pointless async:
266 process.nextTick(function(){
267 callback(null, memo + item)
268 });
269 }, function(err, result){
270 // result is now equal to the last value of memo, which is 6
271 });
272
273---------------------------------------
274
275<a name="reduceRight" />
276### reduceRight(arr, memo, iterator, callback)
277
278__Alias:__ foldr
279
280Same as reduce, only operates on the items in the array in reverse order.
281
282
283---------------------------------------
284
285<a name="detect" />
286### detect(arr, iterator, callback)
287
288Returns the first value in a list that passes an async truth test. The
289iterator is applied in parallel, meaning the first iterator to return true will
290fire the detect callback with that result. That means the result might not be
291the first item in the original array (in terms of order) that passes the test.
292
293If order within the original array is important then look at detectSeries.
294
295__Arguments__
296
297* arr - An array to iterate over.
298* iterator(item, callback) - A truth test to apply to each item in the array.
299 The iterator is passed a callback which must be called once it has completed.
300* callback(result) - A callback which is called as soon as any iterator returns
301 true, or after all the iterator functions have finished. Result will be
302 the first item in the array that passes the truth test (iterator) or the
303 value undefined if none passed.
304
305__Example__
306
307 async.detect(['file1','file2','file3'], path.exists, function(result){
308 // result now equals the first file in the list that exists
309 });
310
311---------------------------------------
312
313<a name="detectSeries" />
314### detectSeries(arr, iterator, callback)
315
316The same as detect, only the iterator is applied to each item in the array
317in series. This means the result is always the first in the original array (in
318terms of array order) that passes the truth test.
319
320
321---------------------------------------
322
323<a name="sortBy" />
324### sortBy(arr, iterator, callback)
325
326Sorts a list by the results of running each value through an async iterator.
327
328__Arguments__
329
330* arr - An array to iterate over.
331* iterator(item, callback) - A function to apply to each item in the array.
332 The iterator is passed a callback which must be called once it has completed
333 with an error (which can be null) and a value to use as the sort criteria.
334* callback(err, results) - A callback which is called after all the iterator
335 functions have finished, or an error has occurred. Results is the items from
336 the original array sorted by the values returned by the iterator calls.
337
338__Example__
339
340 async.sortBy(['file1','file2','file3'], function(file, callback){
341 fs.stat(file, function(err, stats){
342 callback(err, stats.mtime);
343 });
344 }, function(err, results){
345 // results is now the original array of files sorted by
346 // modified date
347 });
348
349
350---------------------------------------
351
352<a name="some" />
353### some(arr, iterator, callback)
354
355__Alias:__ any
356
357Returns true if at least one element in the array satisfies an async test.
358_The callback for each iterator call only accepts a single argument of true or
359false, it does not accept an error argument first!_ This is in-line with the
360way node libraries work with truth tests like path.exists. Once any iterator
361call returns true, the main callback is immediately called.
362
363__Arguments__
364
365* arr - An array to iterate over.
366* iterator(item, callback) - A truth test to apply to each item in the array.
367 The iterator is passed a callback which must be called once it has completed.
368* callback(result) - A callback which is called as soon as any iterator returns
369 true, or after all the iterator functions have finished. Result will be
370 either true or false depending on the values of the async tests.
371
372__Example__
373
374 async.some(['file1','file2','file3'], path.exists, function(result){
375 // if result is true then at least one of the files exists
376 });
377
378---------------------------------------
379
380<a name="every" />
381### every(arr, iterator, callback)
382
383__Alias:__ all
384
385Returns true if every element in the array satisfies an async test.
386_The callback for each iterator call only accepts a single argument of true or
387false, it does not accept an error argument first!_ This is in-line with the
388way node libraries work with truth tests like path.exists.
389
390__Arguments__
391
392* arr - An array to iterate over.
393* iterator(item, callback) - A truth test to apply to each item in the array.
394 The iterator is passed a callback which must be called once it has completed.
395* callback(result) - A callback which is called after all the iterator
396 functions have finished. Result will be either true or false depending on
397 the values of the async tests.
398
399__Example__
400
401 async.every(['file1','file2','file3'], path.exists, function(result){
402 // if result is true then every file exists
403 });
404
405---------------------------------------
406
407<a name="concat" />
408### concat(arr, iterator, callback)
409
410Applies an iterator to each item in a list, concatenating the results. Returns the
411concatenated list. The iterators are called in parallel, and the results are
412concatenated as they return. There is no guarantee that the results array will
413be returned in the original order of the arguments passed to the iterator function.
414
415__Arguments__
416
417* arr - An array to iterate over
418* iterator(item, callback) - A function to apply to each item in the array.
419 The iterator is passed a callback which must be called once it has completed
420 with an error (which can be null) and an array of results.
421* callback(err, results) - A callback which is called after all the iterator
422 functions have finished, or an error has occurred. Results is an array containing
423 the concatenated results of the iterator function.
424
425__Example__
426
427 async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
428 // files is now a list of filenames that exist in the 3 directories
429 });
430
431---------------------------------------
432
433<a name="concatSeries" />
434### concatSeries(arr, iterator, callback)
435
436Same as async.concat, but executes in series instead of parallel.
437
438
439## Flow Control
440
441<a name="series" />
442### series(tasks, [callback])
443
444Run an array of functions in series, each one running once the previous
445function has completed. If any functions in the series pass an error to its
446callback, no more functions are run and the callback for the series is
447immediately called with the value of the error. Once the tasks have completed,
448the results are passed to the final callback as an array.
449
450It is also possible to use an object instead of an array. Each property will be
451run as a function and the results will be passed to the final callback as an object
452instead of an array. This can be a more readable way of handling results from
453async.series.
454
455
456__Arguments__
457
458* tasks - An array or object containing functions to run, each function is passed
459 a callback it must call on completion.
460* callback(err, results) - An optional callback to run once all the functions
461 have completed. This function gets an array of all the arguments passed to
462 the callbacks used in the array.
463
464__Example__
465
466 async.series([
467 function(callback){
468 // do some stuff ...
469 callback(null, 'one');
470 },
471 function(callback){
472 // do some more stuff ...
473 callback(null, 'two');
474 },
475 ],
476 // optional callback
477 function(err, results){
478 // results is now equal to ['one', 'two']
479 });
480
481
482 // an example using an object instead of an array
483 async.series({
484 one: function(callback){
485 setTimeout(function(){
486 callback(null, 1);
487 }, 200);
488 },
489 two: function(callback){
490 setTimeout(function(){
491 callback(null, 2);
492 }, 100);
493 },
494 },
495 function(err, results) {
496 // results is now equals to: {one: 1, two: 2}
497 });
498
499
500---------------------------------------
501
502<a name="parallel" />
503### parallel(tasks, [callback])
504
505Run an array of functions in parallel, without waiting until the previous
506function has completed. If any of the functions pass an error to its
507callback, the main callback is immediately called with the value of the error.
508Once the tasks have completed, the results are passed to the final callback as an
509array.
510
511It is also possible to use an object instead of an array. Each property will be
512run as a function and the results will be passed to the final callback as an object
513instead of an array. This can be a more readable way of handling results from
514async.parallel.
515
516
517__Arguments__
518
519* tasks - An array or object containing functions to run, each function is passed a
520 callback it must call on completion.
521* callback(err, results) - An optional callback to run once all the functions
522 have completed. This function gets an array of all the arguments passed to
523 the callbacks used in the array.
524
525__Example__
526
527 async.parallel([
528 function(callback){
529 setTimeout(function(){
530 callback(null, 'one');
531 }, 200);
532 },
533 function(callback){
534 setTimeout(function(){
535 callback(null, 'two');
536 }, 100);
537 },
538 ],
539 // optional callback
540 function(err, results){
541 // in this case, the results array will equal ['two','one']
542 // because the functions were run in parallel and the second
543 // function had a shorter timeout before calling the callback.
544 });
545
546
547 // an example using an object instead of an array
548 async.parallel({
549 one: function(callback){
550 setTimeout(function(){
551 callback(null, 1);
552 }, 200);
553 },
554 two: function(callback){
555 setTimeout(function(){
556 callback(null, 2);
557 }, 100);
558 },
559 },
560 function(err, results) {
561 // results is now equals to: {one: 1, two: 2}
562 });
563
564
565---------------------------------------
566
567<a name="whilst" />
568### whilst(test, fn, callback)
569
570Repeatedly call fn, while test returns true. Calls the callback when stopped,
571or an error occurs.
572
573__Arguments__
574
575* test() - synchronous truth test to perform before each execution of fn.
576* fn(callback) - A function to call each time the test passes. The function is
577 passed a callback which must be called once it has completed with an optional
578 error as the first argument.
579* callback(err) - A callback which is called after the test fails and repeated
580 execution of fn has stopped.
581
582__Example__
583
584 var count = 0;
585
586 async.whilst(
587 function () { return count < 5; },
588 function (callback) {
589 count++;
590 setTimeout(callback, 1000);
591 },
592 function (err) {
593 // 5 seconds have passed
594 }
595 });
596
597
598---------------------------------------
599
600<a name="until" />
601### until(test, fn, callback)
602
603Repeatedly call fn, until test returns true. Calls the callback when stopped,
604or an error occurs.
605
606The inverse of async.whilst.
607
608
609---------------------------------------
610
611<a name="waterfall" />
612### waterfall(tasks, [callback])
613
614Runs an array of functions in series, each passing their results to the next in
615the array. However, if any of the functions pass an error to the callback, the
616next function is not executed and the main callback is immediately called with
617the error.
618
619__Arguments__
620
621* tasks - An array of functions to run, each function is passed a callback it
622 must call on completion.
623* callback(err) - An optional callback to run once all the functions have
624 completed. This function gets passed any error that may have occurred.
625
626__Example__
627
628 async.waterfall([
629 function(callback){
630 callback(null, 'one', 'two');
631 }
632 function(arg1, arg2, callback){
633 callback(null, 'three');
634 }
635 function(arg1, callback){
636 // arg1 now equals 'three'
637 callback(null, 'done');
638 }
639 ]);
640
641
642---------------------------------------
643
644<a name="auto" />
645### auto(tasks, [callback])
646
647Determines the best order for running functions based on their requirements.
648Each function can optionally depend on other functions being completed first,
649and each function is run as soon as its requirements are satisfied. If any of
650the functions pass and error to their callback, that function will not complete
651(so any other functions depending on it will not run) and the main callback
652will be called immediately with the error.
653
654__Arguments__
655
656* tasks - An object literal containing named functions or an array of
657 requirements, with the function itself the last item in the array. The key
658 used for each function or array is used when specifying requirements. The
659 syntax is easier to understand by looking at the example.
660* callback(err) - An optional callback which is called when all the tasks have
661 been completed. The callback may receive an error as an argument.
662
663__Example__
664
665 async.auto({
666 get_data: function(callback){
667 // async code to get some data
668 },
669 make_folder: function(callback){
670 // async code to create a directory to store a file in
671 // this is run at the same time as getting the data
672 },
673 write_file: ['get_data', 'make_folder', function(callback){
674 // once there is some data and the directory exists,
675 // write the data to a file in the directory
676 }],
677 email_link: ['write_file', function(callback){
678 // once the file is written let's email a link to it...
679 }]
680 });
681
682This is a fairly trivial example, but to do this using the basic parallel and
683series functions would look like this:
684
685 async.parallel([
686 function(callback){
687 // async code to get some data
688 },
689 function(callback){
690 // async code to create a directory to store a file in
691 // this is run at the same time as getting the data
692 }
693 ],
694 function(results){
695 async.series([
696 function(callback){
697 // once there is some data and the directory exists,
698 // write the data to a file in the directory
699 },
700 email_link: ['write_file', function(callback){
701 // once the file is written let's email a link to it...
702 }
703 ]);
704 });
705
706For a complicated series of async tasks using the auto function makes adding
707new tasks much easier and makes the code more readable.
708
709
710---------------------------------------
711
712<a name="iterator" />
713### iterator(tasks)
714
715Creates an iterator function which calls the next function in the array,
716returning a continuation to call the next one after that. Its also possible to
717'peek' the next iterator by doing iterator.next().
718
719This function is used internally by the async module but can be useful when
720you want to manually control the flow of functions in series.
721
722__Arguments__
723
724* tasks - An array of functions to run, each function is passed a callback it
725 must call on completion.
726
727__Example__
728
729 var iterator = async.iterator([
730 function(){ sys.p('one'); },
731 function(){ sys.p('two'); },
732 function(){ sys.p('three'); }
733 ]);
734
735 node> var iterator2 = iterator();
736 'one'
737 node> var iterator3 = iterator2();
738 'two'
739 node> iterator3();
740 'three'
741 node> var nextfn = iterator2.next();
742 node> nextfn();
743 'three'
744
745
746---------------------------------------
747
748<a name="apply" />
749### apply(function, arguments..)
750
751Creates a continuation function with some arguments already applied, a useful
752shorthand when combined with other flow control functions. Any arguments
753passed to the returned function are added to the arguments originally passed
754to apply.
755
756__Arguments__
757
758* function - The function you want to eventually apply all arguments to.
759* arguments... - Any number of arguments to automatically apply when the
760 continuation is called.
761
762__Example__
763
764 // using apply
765
766 async.parallel([
767 async.apply(fs.writeFile, 'testfile1', 'test1'),
768 async.apply(fs.writeFile, 'testfile2', 'test2'),
769 ]);
770
771
772 // the same process without using apply
773
774 async.parallel([
775 function(callback){
776 fs.writeFile('testfile1', 'test1', callback);
777 },
778 function(callback){
779 fs.writeFile('testfile2', 'test2', callback);
780 },
781 ]);
782
783It's possible to pass any number of additional arguments when calling the
784continuation:
785
786 node> var fn = async.apply(sys.puts, 'one');
787 node> fn('two', 'three');
788 one
789 two
790 three
791
792---------------------------------------
793
794<a name="nextTick" />
795### nextTick(callback)
796
797Calls the callback on a later loop around the event loop. In node.js this just
798calls process.nextTick, in the browser it falls back to setTimeout(callback, 0),
799which means other higher priority events may precede the execution of the callback.
800
801This is used internally for browser-compatibility purposes.
802
803__Arguments__
804
805* callback - The function to call on a later loop around the event loop.
806
807__Example__
808
809 var call_order = [];
810 async.nextTick(function(){
811 call_order.push('two');
812 // call_order now equals ['one','two]
813 });
814 call_order.push('one')
815
816
817## Utils
818
819<a name="log" />
820### log(function, arguments)
821
822Logs the result of an async function to the console. Only works in node.js or
823in browsers that support console.log and console.error (such as FF and Chrome).
824If multiple arguments are returned from the async function, console.log is
825called on each argument in order.
826
827__Arguments__
828
829* function - The function you want to eventually apply all arguments to.
830* arguments... - Any number of arguments to apply to the function.
831
832__Example__
833
834 var hello = function(name, callback){
835 setTimeout(function(){
836 callback(null, 'hello ' + name);
837 }, 1000);
838 };
839
840 node> async.log(hello, 'world');
841 'hello world'
842
843
844---------------------------------------
845
846<a name="dir" />
847### dir(function, arguments)
848
849Logs the result of an async function to the console using console.dir to
850display the properties of the resulting object. Only works in node.js or
851in browsers that support console.dir and console.error (such as FF and Chrome).
852If multiple arguments are returned from the async function, console.dir is
853called on each argument in order.
854
855__Arguments__
856
857* function - The function you want to eventually apply all arguments to.
858* arguments... - Any number of arguments to apply to the function.
859
860__Example__
861
862 var hello = function(name, callback){
863 setTimeout(function(){
864 callback(null, {hello: name});
865 }, 1000);
866 };
867
868 node> async.dir(hello, 'world');
869 {hello: 'world'}
870
871
872---------------------------------------
873
874<a name="noConflict" />
875### noConflict()
876
877Changes the value of async back to its original value, returning a reference to the
878async object.