1 | # Async.js
|
2 |
|
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
|
6 | browser.
|
7 |
|
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.
|
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 |
|
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.
|
38 |
|
39 |
|
40 | ## Download
|
41 |
|
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):
|
45 |
|
46 | npm install async
|
47 |
|
48 |
|
49 | ## In the Browser
|
50 |
|
51 | So 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 |
|
102 | Applies an iterator function to each item in an array, in parallel.
|
103 | The iterator is called with an item from the list and a callback for when it
|
104 | has finished. If the iterator passes an error to this callback, the main
|
105 | callback for the forEach function is immediately called with the error.
|
106 |
|
107 | Note, that since this function applies the iterator to each item in parallel
|
108 | there 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 |
|
132 | The same as forEach only the iterator is applied to each item in the array in
|
133 | series. The next iterator is only called once the current one has completed
|
134 | processing. This means the iterator functions will complete in order.
|
135 |
|
136 |
|
137 | ---------------------------------------
|
138 |
|
139 | <a name="map" />
|
140 | ### map(arr, iterator, callback)
|
141 |
|
142 | Produces a new array of values by mapping each value in the given array through
|
143 | the iterator function. The iterator is called with an item from the array and a
|
144 | callback for when it has finished processing. The callback takes 2 arguments,
|
145 | an error and the transformed item from the array. If the iterator passes an
|
146 | error to this callback, the main callback for the map function is immediately
|
147 | called with the error.
|
148 |
|
149 | Note, that since this function applies the iterator to each item in parallel
|
150 | there is no guarantee that the iterator functions will complete in order, however
|
151 | the 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 |
|
174 | The same as map only the iterator is applied to each item in the array in
|
175 | series. The next iterator is only called once the current one has completed
|
176 | processing. 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 |
|
186 | Returns 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
|
188 | false, it does not accept an error argument first!_ This is in-line with the
|
189 | way node libraries work with truth tests like path.exists. This operation is
|
190 | performed in parallel, but the results array will be in the same order as the
|
191 | original.
|
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 |
|
214 | The same as filter only the iterator is applied to each item in the array in
|
215 | series. The next iterator is only called once the current one has completed
|
216 | processing. 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 |
|
223 | The opposite of filter. Removes values that pass an async truth test.
|
224 |
|
225 | ---------------------------------------
|
226 |
|
227 | <a name="rejectSeries" />
|
228 | ### rejectSeries(arr, iterator, callback)
|
229 |
|
230 | The same as filter, only the iterator is applied to each item in the array
|
231 | in series.
|
232 |
|
233 |
|
234 | ---------------------------------------
|
235 |
|
236 | <a name="reduce" />
|
237 | ### reduce(arr, memo, iterator, callback)
|
238 |
|
239 | __aliases:__ inject, foldl
|
240 |
|
241 | Reduces a list of values into a single value using an async iterator to return
|
242 | each successive step. Memo is the initial state of the reduction. This
|
243 | function only operates in series. For performance reasons, it may make sense to
|
244 | split a call to this function into a parallel map, then use the normal
|
245 | Array.prototype.reduce on the results. This function is for situations where
|
246 | each step in the reduction needs to be async, if you can get the data before
|
247 | reducing 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 |
|
280 | Same 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 |
|
288 | Returns the first value in a list that passes an async truth test. The
|
289 | iterator is applied in parallel, meaning the first iterator to return true will
|
290 | fire the detect callback with that result. That means the result might not be
|
291 | the first item in the original array (in terms of order) that passes the test.
|
292 |
|
293 | If 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 |
|
316 | The same as detect, only the iterator is applied to each item in the array
|
317 | in series. This means the result is always the first in the original array (in
|
318 | terms of array order) that passes the truth test.
|
319 |
|
320 |
|
321 | ---------------------------------------
|
322 |
|
323 | <a name="sortBy" />
|
324 | ### sortBy(arr, iterator, callback)
|
325 |
|
326 | Sorts 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 |
|
357 | Returns 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
|
359 | false, it does not accept an error argument first!_ This is in-line with the
|
360 | way node libraries work with truth tests like path.exists. Once any iterator
|
361 | call 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 |
|
385 | Returns 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
|
387 | false, it does not accept an error argument first!_ This is in-line with the
|
388 | way 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 |
|
410 | Applies an iterator to each item in a list, concatenating the results. Returns the
|
411 | concatenated list. The iterators are called in parallel, and the results are
|
412 | concatenated as they return. There is no guarantee that the results array will
|
413 | be 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 |
|
436 | Same 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 |
|
444 | Run an array of functions in series, each one running once the previous
|
445 | function has completed. If any functions in the series pass an error to its
|
446 | callback, no more functions are run and the callback for the series is
|
447 | immediately called with the value of the error. Once the tasks have completed,
|
448 | the results are passed to the final callback as an array.
|
449 |
|
450 | It is also possible to use an object instead of an array. Each property will be
|
451 | run as a function and the results will be passed to the final callback as an object
|
452 | instead of an array. This can be a more readable way of handling results from
|
453 | async.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 |
|
505 | Run an array of functions in parallel, without waiting until the previous
|
506 | function has completed. If any of the functions pass an error to its
|
507 | callback, the main callback is immediately called with the value of the error.
|
508 | Once the tasks have completed, the results are passed to the final callback as an
|
509 | array.
|
510 |
|
511 | It is also possible to use an object instead of an array. Each property will be
|
512 | run as a function and the results will be passed to the final callback as an object
|
513 | instead of an array. This can be a more readable way of handling results from
|
514 | async.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 |
|
570 | Repeatedly call fn, while test returns true. Calls the callback when stopped,
|
571 | or 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 |
|
603 | Repeatedly call fn, until test returns true. Calls the callback when stopped,
|
604 | or an error occurs.
|
605 |
|
606 | The inverse of async.whilst.
|
607 |
|
608 |
|
609 | ---------------------------------------
|
610 |
|
611 | <a name="waterfall" />
|
612 | ### waterfall(tasks, [callback])
|
613 |
|
614 | Runs an array of functions in series, each passing their results to the next in
|
615 | the array. However, if any of the functions pass an error to the callback, the
|
616 | next function is not executed and the main callback is immediately called with
|
617 | the 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 |
|
647 | Determines the best order for running functions based on their requirements.
|
648 | Each function can optionally depend on other functions being completed first,
|
649 | and each function is run as soon as its requirements are satisfied. If any of
|
650 | the 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
|
652 | will 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 |
|
682 | This is a fairly trivial example, but to do this using the basic parallel and
|
683 | series 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 |
|
706 | For a complicated series of async tasks using the auto function makes adding
|
707 | new tasks much easier and makes the code more readable.
|
708 |
|
709 |
|
710 | ---------------------------------------
|
711 |
|
712 | <a name="iterator" />
|
713 | ### iterator(tasks)
|
714 |
|
715 | Creates an iterator function which calls the next function in the array,
|
716 | returning a continuation to call the next one after that. Its also possible to
|
717 | 'peek' the next iterator by doing iterator.next().
|
718 |
|
719 | This function is used internally by the async module but can be useful when
|
720 | you 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 |
|
751 | Creates a continuation function with some arguments already applied, a useful
|
752 | shorthand when combined with other flow control functions. Any arguments
|
753 | passed to the returned function are added to the arguments originally passed
|
754 | to 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 |
|
783 | It's possible to pass any number of additional arguments when calling the
|
784 | continuation:
|
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 |
|
797 | Calls the callback on a later loop around the event loop. In node.js this just
|
798 | calls process.nextTick, in the browser it falls back to setTimeout(callback, 0),
|
799 | which means other higher priority events may precede the execution of the callback.
|
800 |
|
801 | This 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 |
|
822 | Logs the result of an async function to the console. Only works in node.js or
|
823 | in browsers that support console.log and console.error (such as FF and Chrome).
|
824 | If multiple arguments are returned from the async function, console.log is
|
825 | called 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 |
|
849 | Logs the result of an async function to the console using console.dir to
|
850 | display the properties of the resulting object. Only works in node.js or
|
851 | in browsers that support console.dir and console.error (such as FF and Chrome).
|
852 | If multiple arguments are returned from the async function, console.dir is
|
853 | called 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 |
|
877 | Changes the value of async back to its original value, returning a reference to the
|
878 | async object.
|