fsevents 1.0.0 → 1.0.1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of fsevents might be problematic. Click here for more details.

Files changed (149) hide show
  1. package/node_modules/node-pre-gyp/CHANGELOG.md +9 -0
  2. package/node_modules/node-pre-gyp/lib/util/abi_crosswalk.json +32 -0
  3. package/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/package.json +2 -1
  4. package/node_modules/node-pre-gyp/node_modules/nopt/README.md +8 -7
  5. package/node_modules/node-pre-gyp/node_modules/nopt/package.json +16 -12
  6. package/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/package.json +1 -1
  7. package/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/package.json +1 -1
  8. package/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/package.json +1 -1
  9. package/node_modules/node-pre-gyp/node_modules/rc/lib/utils.js +2 -2
  10. package/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/index.js +14 -2
  11. package/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/package.json +10 -9
  12. package/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/bool.js +23 -0
  13. package/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/kv_short.js +16 -0
  14. package/node_modules/node-pre-gyp/node_modules/rc/package.json +9 -8
  15. package/node_modules/node-pre-gyp/node_modules/request/.travis.yml +1 -0
  16. package/node_modules/node-pre-gyp/node_modules/request/CHANGELOG.md +22 -2
  17. package/node_modules/node-pre-gyp/node_modules/request/README.md +42 -10
  18. package/node_modules/node-pre-gyp/node_modules/request/index.js +4 -0
  19. package/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/package.json +1 -1
  20. package/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/package.json +1 -1
  21. package/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/package.json +1 -1
  22. package/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/process-nextick-args/index.js +1 -1
  23. package/node_modules/node-pre-gyp/node_modules/request/node_modules/{form-data/node_modules/async/LICENSE → bl/node_modules/readable-stream/node_modules/process-nextick-args/license.md} +6 -6
  24. package/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/process-nextick-args/package.json +10 -9
  25. package/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/process-nextick-args/test.js +7 -0
  26. package/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/package.json +2 -1
  27. package/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/package.json +2 -1
  28. package/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/package.json +2 -1
  29. package/node_modules/node-pre-gyp/node_modules/request/node_modules/extend/package.json +2 -1
  30. package/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/package.json +1 -1
  31. package/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/Readme.md +44 -9
  32. package/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/lib/form_data.js +48 -25
  33. package/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/async/lib/async.js +13 -7
  34. package/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/async/package.json +26 -11
  35. package/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/package.json +29 -20
  36. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/README.md +4 -1
  37. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/browser/bluebird.js +35 -11
  38. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/browser/bluebird.min.js +5 -5
  39. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/debuggability.js +2 -0
  40. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/direct_resolve.js +2 -0
  41. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise.js +5 -1
  42. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promisify.js +10 -5
  43. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/using.js +14 -3
  44. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/package.json +9 -8
  45. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/chalk/index.js +2 -2
  46. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/chalk/node_modules/escape-string-regexp/package.json +1 -1
  47. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/chalk/package.json +22 -15
  48. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/chalk/readme.md +3 -2
  49. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/package.json +1 -1
  50. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/README.md +1 -1
  51. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/package.json +1 -1
  52. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/package.json +1 -1
  53. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/.travis.yml +6 -2
  54. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/README.md +3 -2
  55. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/jsonpointer.js +7 -10
  56. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/package.json +24 -20
  57. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/test.js +11 -13
  58. package/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/package.json +11 -10
  59. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/.travis.yml +3 -2
  60. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/lib/index.js +39 -28
  61. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/package.json +11 -12
  62. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/test/index.js +1 -1
  63. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/.npmignore +18 -18
  64. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/.travis.yml +8 -5
  65. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/README.md +2 -0
  66. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/package.json +24 -28
  67. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/test/index.js +57 -63
  68. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/.travis.yml +2 -2
  69. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/LICENSE +0 -0
  70. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/README.md +16 -6
  71. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/images/hoek.png +0 -0
  72. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/lib/escape.js +0 -0
  73. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/lib/index.js +24 -8
  74. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/package.json +13 -13
  75. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/test/escaper.js +0 -0
  76. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/test/index.js +866 -778
  77. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/test/modules/test1.js +0 -0
  78. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/test/modules/test2.js +0 -0
  79. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/test/modules/test3.js +0 -0
  80. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/package.json +1 -1
  81. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/package.json +2 -1
  82. package/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/assert-plus/package.json +1 -1
  83. package/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/package.json +1 -1
  84. package/node_modules/node-pre-gyp/node_modules/request/node_modules/isstream/package.json +1 -1
  85. package/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/HISTORY.md +24 -0
  86. package/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/index.js +1 -1
  87. package/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/node_modules/mime-db/HISTORY.md +33 -0
  88. package/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/node_modules/mime-db/db.json +50 -0
  89. package/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/node_modules/mime-db/package.json +12 -13
  90. package/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/package.json +9 -10
  91. package/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/package.json +1 -1
  92. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.npmignore +0 -1
  93. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.travis.yml +3 -2
  94. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/CHANGELOG.md +13 -2
  95. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/README.md +11 -4
  96. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/bower.json +1 -1
  97. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/component.json +15 -0
  98. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/dist/qs.js +523 -0
  99. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/parse.js +3 -2
  100. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/stringify.js +28 -7
  101. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/package.json +20 -18
  102. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/parse.js +14 -14
  103. package/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/stringify.js +23 -1
  104. package/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/package.json +1 -1
  105. package/node_modules/node-pre-gyp/node_modules/request/package.json +12 -12
  106. package/node_modules/node-pre-gyp/node_modules/request/request.js +51 -30
  107. package/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/package.json +1 -1
  108. package/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/package.json +3 -2
  109. package/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/package.json +2 -1
  110. package/node_modules/node-pre-gyp/node_modules/rimraf/package.json +9 -8
  111. package/node_modules/node-pre-gyp/node_modules/rimraf/rimraf.js +1 -1
  112. package/node_modules/node-pre-gyp/node_modules/semver/package.json +10 -12
  113. package/node_modules/node-pre-gyp/node_modules/semver/semver.js +1 -0
  114. package/node_modules/node-pre-gyp/node_modules/semver/test/index.js +21 -8
  115. package/node_modules/node-pre-gyp/node_modules/tar/lib/entry.js +7 -0
  116. package/node_modules/node-pre-gyp/node_modules/tar/lib/parse.js +5 -1
  117. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/fs.js +21 -11
  118. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js +208 -115
  119. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/legacy-streams.js +118 -0
  120. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/package.json +18 -17
  121. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/polyfills.js +130 -133
  122. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/package.json +18 -14
  123. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/package.json +1 -1
  124. package/node_modules/node-pre-gyp/node_modules/tar/package.json +22 -15
  125. package/node_modules/node-pre-gyp/node_modules/tar/test/parse-discard.js +29 -0
  126. package/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/package.json +1 -1
  127. package/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/README.md +12 -2
  128. package/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js +48 -4
  129. package/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/package.json +9 -9
  130. package/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/basic.js +26 -25
  131. package/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/serialize.js +216 -0
  132. package/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/package.json +1 -1
  133. package/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/package.json +1 -1
  134. package/node_modules/node-pre-gyp/package.json +10 -10
  135. package/package.json +2 -2
  136. package/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/async/.jscsrc +0 -3
  137. package/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/async/CHANGELOG.md +0 -81
  138. package/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/async/README.md +0 -1789
  139. package/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/async/support/sync-package-managers.js +0 -53
  140. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/Makefile +0 -9
  141. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/index.js +0 -1
  142. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/Makefile +0 -8
  143. package/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/index.js +0 -1
  144. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/.npmignore +0 -1
  145. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/LICENSE +0 -15
  146. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/max-open.js +0 -69
  147. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/open.js +0 -39
  148. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/readdir-sort.js +0 -20
  149. package/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/write-then-read.js +0 -47
@@ -1,1789 +0,0 @@
1
- # Async.js
2
-
3
- [![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async)
4
- [![NPM version](http://img.shields.io/npm/v/async.svg)](https://www.npmjs.org/package/async)
5
- [![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master)
6
- [![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
7
-
8
-
9
- Async is a utility module which provides straight-forward, powerful functions
10
- for working with asynchronous JavaScript. Although originally designed for
11
- use with [Node.js](http://nodejs.org) and installable via `npm install async`,
12
- it can also be used directly in the browser.
13
-
14
- Async is also installable via:
15
-
16
- - [bower](http://bower.io/): `bower install async`
17
- - [component](https://github.com/component/component): `component install
18
- caolan/async`
19
- - [jam](http://jamjs.org/): `jam install async`
20
- - [spm](http://spmjs.io/): `spm install async`
21
-
22
- Async provides around 20 functions that include the usual 'functional'
23
- suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns
24
- for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these
25
- functions assume you follow the Node.js convention of providing a single
26
- callback as the last argument of your `async` function.
27
-
28
-
29
- ## Quick Examples
30
-
31
- ```javascript
32
- async.map(['file1','file2','file3'], fs.stat, function(err, results){
33
- // results is now an array of stats for each file
34
- });
35
-
36
- async.filter(['file1','file2','file3'], fs.exists, function(results){
37
- // results now equals an array of the existing files
38
- });
39
-
40
- async.parallel([
41
- function(){ ... },
42
- function(){ ... }
43
- ], callback);
44
-
45
- async.series([
46
- function(){ ... },
47
- function(){ ... }
48
- ]);
49
- ```
50
-
51
- There are many more functions available so take a look at the docs below for a
52
- full list. This module aims to be comprehensive, so if you feel anything is
53
- missing please create a GitHub issue for it.
54
-
55
- ## Common Pitfalls <sub>[(StackOverflow)](http://stackoverflow.com/questions/tagged/async.js)</sub>
56
- ### Synchronous iteration functions
57
-
58
- If you get an error like `RangeError: Maximum call stack size exceeded.` or other stack overflow issues when using async, you are likely using a synchronous iterator. By *synchronous* we mean a function that calls its callback on the same tick in the javascript event loop, without doing any I/O or using any timers. Calling many callbacks iteratively will quickly overflow the stack. If you run into this issue, just defer your callback with `async.nextTick` to start a new call stack on the next tick of the event loop.
59
-
60
- This can also arise by accident if you callback early in certain cases:
61
-
62
- ```js
63
- async.eachSeries(hugeArray, function iterator(item, callback) {
64
- if (inCache(item)) {
65
- callback(null, cache[item]); // if many items are cached, you'll overflow
66
- } else {
67
- doSomeIO(item, callback);
68
- }
69
- }, function done() {
70
- //...
71
- });
72
- ```
73
-
74
- Just change it to:
75
-
76
- ```js
77
- async.eachSeries(hugeArray, function iterator(item, callback) {
78
- if (inCache(item)) {
79
- async.setImmediate(function () {
80
- callback(null, cache[item]);
81
- });
82
- } else {
83
- doSomeIO(item, callback);
84
- //...
85
- ```
86
-
87
- Async guards against synchronous functions in some, but not all, cases. If you are still running into stack overflows, you can defer as suggested above, or wrap functions with [`async.ensureAsync`](#ensureAsync) Functions that are asynchronous by their nature do not have this problem and don't need the extra callback deferral.
88
-
89
- If javascript's event loop is still a bit nebulous, check out [this article](http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/) or [this talk](http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html) for more detailed information about how it works.
90
-
91
-
92
- ### Multiple callbacks
93
-
94
- Make sure to always `return` when calling a callback early, otherwise you will cause multiple callbacks and unpredictable behavior in many cases.
95
-
96
- ```js
97
- async.waterfall([
98
- function (callback) {
99
- getSomething(options, function (err, result) {
100
- if (err) {
101
- callback(new Error("failed getting something:" + err.message));
102
- // we should return here
103
- }
104
- // since we did not return, this callback still will be called and
105
- // `processData` will be called twice
106
- callback(result);
107
- });
108
- },
109
- processData
110
- ], done)
111
- ```
112
-
113
- It is always good practice to `return callback(err, result)` whenever a callback call is not the last statement of a function.
114
-
115
-
116
- ### Binding a context to an iterator
117
-
118
- This section is really about `bind`, not about `async`. If you are wondering how to
119
- make `async` execute your iterators in a given context, or are confused as to why
120
- a method of another library isn't working as an iterator, study this example:
121
-
122
- ```js
123
- // Here is a simple object with an (unnecessarily roundabout) squaring method
124
- var AsyncSquaringLibrary = {
125
- squareExponent: 2,
126
- square: function(number, callback){
127
- var result = Math.pow(number, this.squareExponent);
128
- setTimeout(function(){
129
- callback(null, result);
130
- }, 200);
131
- }
132
- };
133
-
134
- async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){
135
- // result is [NaN, NaN, NaN]
136
- // This fails because the `this.squareExponent` expression in the square
137
- // function is not evaluated in the context of AsyncSquaringLibrary, and is
138
- // therefore undefined.
139
- });
140
-
141
- async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){
142
- // result is [1, 4, 9]
143
- // With the help of bind we can attach a context to the iterator before
144
- // passing it to async. Now the square function will be executed in its
145
- // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent`
146
- // will be as expected.
147
- });
148
- ```
149
-
150
- ## Download
151
-
152
- The source is available for download from
153
- [GitHub](https://github.com/caolan/async/blob/master/lib/async.js).
154
- Alternatively, you can install using Node Package Manager (`npm`):
155
-
156
- npm install async
157
-
158
- As well as using Bower:
159
-
160
- bower install async
161
-
162
- __Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed
163
-
164
- ## In the Browser
165
-
166
- So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5.
167
-
168
- Usage:
169
-
170
- ```html
171
- <script type="text/javascript" src="async.js"></script>
172
- <script type="text/javascript">
173
-
174
- async.map(data, asyncProcess, function(err, results){
175
- alert(results);
176
- });
177
-
178
- </script>
179
- ```
180
-
181
- ## Documentation
182
-
183
- Some functions are also available in the following forms:
184
- * `<name>Series` - the same as `<name>` but runs only a single async operation at a time
185
- * `<name>Limit` - the same as `<name>` but runs a maximum of `limit` async operations at a time
186
-
187
- ### Collections
188
-
189
- * [`each`](#each), `eachSeries`, `eachLimit`
190
- * [`forEachOf`](#forEachOf), `forEachOfSeries`, `forEachOfLimit`
191
- * [`map`](#map), `mapSeries`, `mapLimit`
192
- * [`filter`](#filter), `filterSeries`, `filterLimit`
193
- * [`reject`](#reject), `rejectSeries`, `rejectLimit`
194
- * [`reduce`](#reduce), [`reduceRight`](#reduceRight)
195
- * [`detect`](#detect), `detectSeries`, `detectLimit`
196
- * [`sortBy`](#sortBy)
197
- * [`some`](#some), `someLimit`
198
- * [`every`](#every), `everyLimit`
199
- * [`concat`](#concat), `concatSeries`
200
-
201
- ### Control Flow
202
-
203
- * [`series`](#seriestasks-callback)
204
- * [`parallel`](#parallel), `parallelLimit`
205
- * [`whilst`](#whilst), [`doWhilst`](#doWhilst)
206
- * [`until`](#until), [`doUntil`](#doUntil)
207
- * [`during`](#during), [`doDuring`](#doDuring)
208
- * [`forever`](#forever)
209
- * [`waterfall`](#waterfall)
210
- * [`compose`](#compose)
211
- * [`seq`](#seq)
212
- * [`applyEach`](#applyEach), `applyEachSeries`
213
- * [`queue`](#queue), [`priorityQueue`](#priorityQueue)
214
- * [`cargo`](#cargo)
215
- * [`auto`](#auto)
216
- * [`retry`](#retry)
217
- * [`iterator`](#iterator)
218
- * [`times`](#times), `timesSeries`, `timesLimit`
219
-
220
- ### Utils
221
-
222
- * [`apply`](#apply)
223
- * [`nextTick`](#nextTick)
224
- * [`memoize`](#memoize)
225
- * [`unmemoize`](#unmemoize)
226
- * [`ensureAsync`](#ensureAsync)
227
- * [`constant`](#constant)
228
- * [`asyncify`](#asyncify)
229
- * [`wrapSync`](#wrapSync)
230
- * [`log`](#log)
231
- * [`dir`](#dir)
232
- * [`noConflict`](#noConflict)
233
-
234
- ## Collections
235
-
236
- <a name="forEach" />
237
- <a name="each" />
238
- ### each(arr, iterator, [callback])
239
-
240
- Applies the function `iterator` to each item in `arr`, in parallel.
241
- The `iterator` is called with an item from the list, and a callback for when it
242
- has finished. If the `iterator` passes an error to its `callback`, the main
243
- `callback` (for the `each` function) is immediately called with the error.
244
-
245
- Note, that since this function applies `iterator` to each item in parallel,
246
- there is no guarantee that the iterator functions will complete in order.
247
-
248
- __Arguments__
249
-
250
- * `arr` - An array to iterate over.
251
- * `iterator(item, callback)` - A function to apply to each item in `arr`.
252
- The iterator is passed a `callback(err)` which must be called once it has
253
- completed. If no error has occurred, the `callback` should be run without
254
- arguments or with an explicit `null` argument. The array index is not passed
255
- to the iterator. If you need the index, use [`forEachOf`](#forEachOf).
256
- * `callback(err)` - *Optional* A callback which is called when all `iterator` functions
257
- have finished, or an error occurs.
258
-
259
- __Examples__
260
-
261
-
262
- ```js
263
- // assuming openFiles is an array of file names and saveFile is a function
264
- // to save the modified contents of that file:
265
-
266
- async.each(openFiles, saveFile, function(err){
267
- // if any of the saves produced an error, err would equal that error
268
- });
269
- ```
270
-
271
- ```js
272
- // assuming openFiles is an array of file names
273
-
274
- async.each(openFiles, function(file, callback) {
275
-
276
- // Perform operation on file here.
277
- console.log('Processing file ' + file);
278
-
279
- if( file.length > 32 ) {
280
- console.log('This file name is too long');
281
- callback('File name too long');
282
- } else {
283
- // Do work to process file here
284
- console.log('File processed');
285
- callback();
286
- }
287
- }, function(err){
288
- // if any of the file processing produced an error, err would equal that error
289
- if( err ) {
290
- // One of the iterations produced an error.
291
- // All processing will now stop.
292
- console.log('A file failed to process');
293
- } else {
294
- console.log('All files have been processed successfully');
295
- }
296
- });
297
- ```
298
-
299
- __Related__
300
-
301
- * eachSeries(arr, iterator, [callback])
302
- * eachLimit(arr, limit, iterator, [callback])
303
-
304
- ---------------------------------------
305
-
306
- <a name="forEachOf" />
307
- <a name="eachOf" />
308
-
309
- ### forEachOf(obj, iterator, [callback])
310
-
311
- Like `each`, except that it iterates over objects, and passes the key as the second argument to the iterator.
312
-
313
- __Arguments__
314
-
315
- * `obj` - An object or array to iterate over.
316
- * `iterator(item, key, callback)` - A function to apply to each item in `obj`.
317
- The `key` is the item's key, or index in the case of an array. The iterator is
318
- passed a `callback(err)` which must be called once it has completed. If no
319
- error has occurred, the callback should be run without arguments or with an
320
- explicit `null` argument.
321
- * `callback(err)` - *Optional* A callback which is called when all `iterator` functions have finished, or an error occurs.
322
-
323
- __Example__
324
-
325
- ```js
326
- var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
327
- var configs = {};
328
-
329
- async.forEachOf(obj, function (value, key, callback) {
330
- fs.readFile(__dirname + value, "utf8", function (err, data) {
331
- if (err) return callback(err);
332
- try {
333
- configs[key] = JSON.parse(data);
334
- } catch (e) {
335
- return callback(e);
336
- }
337
- callback();
338
- })
339
- }, function (err) {
340
- if (err) console.error(err.message);
341
- // configs is now a map of JSON data
342
- doSomethingWith(configs);
343
- })
344
- ```
345
-
346
- __Related__
347
-
348
- * forEachOfSeries(obj, iterator, [callback])
349
- * forEachOfLimit(obj, limit, iterator, [callback])
350
-
351
- ---------------------------------------
352
-
353
- <a name="map" />
354
- ### map(arr, iterator, [callback])
355
-
356
- Produces a new array of values by mapping each value in `arr` through
357
- the `iterator` function. The `iterator` is called with an item from `arr` and a
358
- callback for when it has finished processing. Each of these callback takes 2 arguments:
359
- an `error`, and the transformed item from `arr`. If `iterator` passes an error to its
360
- callback, the main `callback` (for the `map` function) is immediately called with the error.
361
-
362
- Note, that since this function applies the `iterator` to each item in parallel,
363
- there is no guarantee that the `iterator` functions will complete in order.
364
- However, the results array will be in the same order as the original `arr`.
365
-
366
- __Arguments__
367
-
368
- * `arr` - An array to iterate over.
369
- * `iterator(item, callback)` - A function to apply to each item in `arr`.
370
- The iterator is passed a `callback(err, transformed)` which must be called once
371
- it has completed with an error (which can be `null`) and a transformed item.
372
- * `callback(err, results)` - *Optional* A callback which is called when all `iterator`
373
- functions have finished, or an error occurs. Results is an array of the
374
- transformed items from the `arr`.
375
-
376
- __Example__
377
-
378
- ```js
379
- async.map(['file1','file2','file3'], fs.stat, function(err, results){
380
- // results is now an array of stats for each file
381
- });
382
- ```
383
-
384
- __Related__
385
- * mapSeries(arr, iterator, [callback])
386
- * mapLimit(arr, limit, iterator, [callback])
387
-
388
- ---------------------------------------
389
-
390
- <a name="select" />
391
- <a name="filter" />
392
- ### filter(arr, iterator, [callback])
393
-
394
- __Alias:__ `select`
395
-
396
- Returns a new array of all the values in `arr` which pass an async truth test.
397
- _The callback for each `iterator` call only accepts a single argument of `true` or
398
- `false`; it does not accept an error argument first!_ This is in-line with the
399
- way node libraries work with truth tests like `fs.exists`. This operation is
400
- performed in parallel, but the results array will be in the same order as the
401
- original.
402
-
403
- __Arguments__
404
-
405
- * `arr` - An array to iterate over.
406
- * `iterator(item, callback)` - A truth test to apply to each item in `arr`.
407
- The `iterator` is passed a `callback(truthValue)`, which must be called with a
408
- boolean argument once it has completed.
409
- * `callback(results)` - *Optional* A callback which is called after all the `iterator`
410
- functions have finished.
411
-
412
- __Example__
413
-
414
- ```js
415
- async.filter(['file1','file2','file3'], fs.exists, function(results){
416
- // results now equals an array of the existing files
417
- });
418
- ```
419
-
420
- __Related__
421
-
422
- * filterSeries(arr, iterator, [callback])
423
- * filterLimit(arr, limit, iterator, [callback])
424
-
425
- ---------------------------------------
426
-
427
- <a name="reject" />
428
- ### reject(arr, iterator, [callback])
429
-
430
- The opposite of [`filter`](#filter). Removes values that pass an `async` truth test.
431
-
432
- __Related__
433
-
434
- * rejectSeries(arr, iterator, [callback])
435
- * rejectLimit(arr, limit, iterator, [callback])
436
-
437
- ---------------------------------------
438
-
439
- <a name="reduce" />
440
- ### reduce(arr, memo, iterator, [callback])
441
-
442
- __Aliases:__ `inject`, `foldl`
443
-
444
- Reduces `arr` into a single value using an async `iterator` to return
445
- each successive step. `memo` is the initial state of the reduction.
446
- This function only operates in series.
447
-
448
- For performance reasons, it may make sense to split a call to this function into
449
- a parallel map, and then use the normal `Array.prototype.reduce` on the results.
450
- This function is for situations where each step in the reduction needs to be async;
451
- if you can get the data before reducing it, then it's probably a good idea to do so.
452
-
453
- __Arguments__
454
-
455
- * `arr` - An array to iterate over.
456
- * `memo` - The initial state of the reduction.
457
- * `iterator(memo, item, callback)` - A function applied to each item in the
458
- array to produce the next step in the reduction. The `iterator` is passed a
459
- `callback(err, reduction)` which accepts an optional error as its first
460
- argument, and the state of the reduction as the second. If an error is
461
- passed to the callback, the reduction is stopped and the main `callback` is
462
- immediately called with the error.
463
- * `callback(err, result)` - *Optional* A callback which is called after all the `iterator`
464
- functions have finished. Result is the reduced value.
465
-
466
- __Example__
467
-
468
- ```js
469
- async.reduce([1,2,3], 0, function(memo, item, callback){
470
- // pointless async:
471
- process.nextTick(function(){
472
- callback(null, memo + item)
473
- });
474
- }, function(err, result){
475
- // result is now equal to the last value of memo, which is 6
476
- });
477
- ```
478
-
479
- ---------------------------------------
480
-
481
- <a name="reduceRight" />
482
- ### reduceRight(arr, memo, iterator, [callback])
483
-
484
- __Alias:__ `foldr`
485
-
486
- Same as [`reduce`](#reduce), only operates on `arr` in reverse order.
487
-
488
-
489
- ---------------------------------------
490
-
491
- <a name="detect" />
492
- ### detect(arr, iterator, [callback])
493
-
494
- Returns the first value in `arr` that passes an async truth test. The
495
- `iterator` is applied in parallel, meaning the first iterator to return `true` will
496
- fire the detect `callback` with that result. That means the result might not be
497
- the first item in the original `arr` (in terms of order) that passes the test.
498
-
499
- If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries).
500
-
501
- __Arguments__
502
-
503
- * `arr` - An array to iterate over.
504
- * `iterator(item, callback)` - A truth test to apply to each item in `arr`.
505
- The iterator is passed a `callback(truthValue)` which must be called with a
506
- boolean argument once it has completed. **Note: this callback does not take an error as its first argument.**
507
- * `callback(result)` - *Optional* A callback which is called as soon as any iterator returns
508
- `true`, or after all the `iterator` functions have finished. Result will be
509
- the first item in the array that passes the truth test (iterator) or the
510
- value `undefined` if none passed. **Note: this callback does not take an error as its first argument.**
511
-
512
- __Example__
513
-
514
- ```js
515
- async.detect(['file1','file2','file3'], fs.exists, function(result){
516
- // result now equals the first file in the list that exists
517
- });
518
- ```
519
-
520
- __Related__
521
-
522
- * detectSeries(arr, iterator, [callback])
523
- * detectLimit(arr, limit, iterator, [callback])
524
-
525
- ---------------------------------------
526
-
527
- <a name="sortBy" />
528
- ### sortBy(arr, iterator, [callback])
529
-
530
- Sorts a list by the results of running each `arr` value through an async `iterator`.
531
-
532
- __Arguments__
533
-
534
- * `arr` - An array to iterate over.
535
- * `iterator(item, callback)` - A function to apply to each item in `arr`.
536
- The iterator is passed a `callback(err, sortValue)` which must be called once it
537
- has completed with an error (which can be `null`) and a value to use as the sort
538
- criteria.
539
- * `callback(err, results)` - *Optional* A callback which is called after all the `iterator`
540
- functions have finished, or an error occurs. Results is the items from
541
- the original `arr` sorted by the values returned by the `iterator` calls.
542
-
543
- __Example__
544
-
545
- ```js
546
- async.sortBy(['file1','file2','file3'], function(file, callback){
547
- fs.stat(file, function(err, stats){
548
- callback(err, stats.mtime);
549
- });
550
- }, function(err, results){
551
- // results is now the original array of files sorted by
552
- // modified date
553
- });
554
- ```
555
-
556
- __Sort Order__
557
-
558
- By modifying the callback parameter the sorting order can be influenced:
559
-
560
- ```js
561
- //ascending order
562
- async.sortBy([1,9,3,5], function(x, callback){
563
- callback(null, x);
564
- }, function(err,result){
565
- //result callback
566
- } );
567
-
568
- //descending order
569
- async.sortBy([1,9,3,5], function(x, callback){
570
- callback(null, x*-1); //<- x*-1 instead of x, turns the order around
571
- }, function(err,result){
572
- //result callback
573
- } );
574
- ```
575
-
576
- ---------------------------------------
577
-
578
- <a name="some" />
579
- ### some(arr, iterator, [callback])
580
-
581
- __Alias:__ `any`
582
-
583
- Returns `true` if at least one element in the `arr` satisfies an async test.
584
- _The callback for each iterator call only accepts a single argument of `true` or
585
- `false`; it does not accept an error argument first!_ This is in-line with the
586
- way node libraries work with truth tests like `fs.exists`. Once any iterator
587
- call returns `true`, the main `callback` is immediately called.
588
-
589
- __Arguments__
590
-
591
- * `arr` - An array to iterate over.
592
- * `iterator(item, callback)` - A truth test to apply to each item in the array
593
- in parallel. The iterator is passed a `callback(truthValue)`` which must be
594
- called with a boolean argument once it has completed.
595
- * `callback(result)` - *Optional* A callback which is called as soon as any iterator returns
596
- `true`, or after all the iterator functions have finished. Result will be
597
- either `true` or `false` depending on the values of the async tests.
598
-
599
- **Note: the callbacks do not take an error as their first argument.**
600
- __Example__
601
-
602
- ```js
603
- async.some(['file1','file2','file3'], fs.exists, function(result){
604
- // if result is true then at least one of the files exists
605
- });
606
- ```
607
-
608
- __Related__
609
-
610
- * someLimit(arr, limit, iterator, callback)
611
-
612
- ---------------------------------------
613
-
614
- <a name="every" />
615
- ### every(arr, iterator, [callback])
616
-
617
- __Alias:__ `all`
618
-
619
- Returns `true` if every element in `arr` satisfies an async test.
620
- _The callback for each `iterator` call only accepts a single argument of `true` or
621
- `false`; it does not accept an error argument first!_ This is in-line with the
622
- way node libraries work with truth tests like `fs.exists`.
623
-
624
- __Arguments__
625
-
626
- * `arr` - An array to iterate over.
627
- * `iterator(item, callback)` - A truth test to apply to each item in the array
628
- in parallel. The iterator is passed a `callback(truthValue)` which must be
629
- called with a boolean argument once it has completed.
630
- * `callback(result)` - *Optional* A callback which is called after all the `iterator`
631
- functions have finished. Result will be either `true` or `false` depending on
632
- the values of the async tests.
633
-
634
- **Note: the callbacks do not take an error as their first argument.**
635
-
636
- __Example__
637
-
638
- ```js
639
- async.every(['file1','file2','file3'], fs.exists, function(result){
640
- // if result is true then every file exists
641
- });
642
- ```
643
-
644
- __Related__
645
-
646
- * everyLimit(arr, limit, iterator, callback)
647
-
648
- ---------------------------------------
649
-
650
- <a name="concat" />
651
- ### concat(arr, iterator, [callback])
652
-
653
- Applies `iterator` to each item in `arr`, concatenating the results. Returns the
654
- concatenated list. The `iterator`s are called in parallel, and the results are
655
- concatenated as they return. There is no guarantee that the results array will
656
- be returned in the original order of `arr` passed to the `iterator` function.
657
-
658
- __Arguments__
659
-
660
- * `arr` - An array to iterate over.
661
- * `iterator(item, callback)` - A function to apply to each item in `arr`.
662
- The iterator is passed a `callback(err, results)` which must be called once it
663
- has completed with an error (which can be `null`) and an array of results.
664
- * `callback(err, results)` - *Optional* A callback which is called after all the `iterator`
665
- functions have finished, or an error occurs. Results is an array containing
666
- the concatenated results of the `iterator` function.
667
-
668
- __Example__
669
-
670
- ```js
671
- async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
672
- // files is now a list of filenames that exist in the 3 directories
673
- });
674
- ```
675
-
676
- __Related__
677
-
678
- * concatSeries(arr, iterator, [callback])
679
-
680
-
681
- ## Control Flow
682
-
683
- <a name="series" />
684
- ### series(tasks, [callback])
685
-
686
- Run the functions in the `tasks` array in series, each one running once the previous
687
- function has completed. If any functions in the series pass an error to its
688
- callback, no more functions are run, and `callback` is immediately called with the value of the error.
689
- Otherwise, `callback` receives an array of results when `tasks` have completed.
690
-
691
- It is also possible to use an object instead of an array. Each property will be
692
- run as a function, and the results will be passed to the final `callback` as an object
693
- instead of an array. This can be a more readable way of handling results from
694
- [`series`](#series).
695
-
696
- **Note** that while many implementations preserve the order of object properties, the
697
- [ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
698
- explicitly states that
699
-
700
- > The mechanics and order of enumerating the properties is not specified.
701
-
702
- So if you rely on the order in which your series of functions are executed, and want
703
- this to work on all platforms, consider using an array.
704
-
705
- __Arguments__
706
-
707
- * `tasks` - An array or object containing functions to run, each function is passed
708
- a `callback(err, result)` it must call on completion with an error `err` (which can
709
- be `null`) and an optional `result` value.
710
- * `callback(err, results)` - An optional callback to run once all the functions
711
- have completed. This function gets a results array (or object) containing all
712
- the result arguments passed to the `task` callbacks.
713
-
714
- __Example__
715
-
716
- ```js
717
- async.series([
718
- function(callback){
719
- // do some stuff ...
720
- callback(null, 'one');
721
- },
722
- function(callback){
723
- // do some more stuff ...
724
- callback(null, 'two');
725
- }
726
- ],
727
- // optional callback
728
- function(err, results){
729
- // results is now equal to ['one', 'two']
730
- });
731
-
732
-
733
- // an example using an object instead of an array
734
- async.series({
735
- one: function(callback){
736
- setTimeout(function(){
737
- callback(null, 1);
738
- }, 200);
739
- },
740
- two: function(callback){
741
- setTimeout(function(){
742
- callback(null, 2);
743
- }, 100);
744
- }
745
- },
746
- function(err, results) {
747
- // results is now equal to: {one: 1, two: 2}
748
- });
749
- ```
750
-
751
- ---------------------------------------
752
-
753
- <a name="parallel" />
754
- ### parallel(tasks, [callback])
755
-
756
- Run the `tasks` array of functions in parallel, without waiting until the previous
757
- function has completed. If any of the functions pass an error to its
758
- callback, the main `callback` is immediately called with the value of the error.
759
- Once the `tasks` have completed, the results are passed to the final `callback` as an
760
- array.
761
-
762
- **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about parallel execution of code. If your tasks do not use any timers or perform any I/O, they will actually be executed in series. Any synchronous setup sections for each task will happen one after the other. JavaScript remains single-threaded.
763
-
764
- It is also possible to use an object instead of an array. Each property will be
765
- run as a function and the results will be passed to the final `callback` as an object
766
- instead of an array. This can be a more readable way of handling results from
767
- [`parallel`](#parallel).
768
-
769
-
770
- __Arguments__
771
-
772
- * `tasks` - An array or object containing functions to run. Each function is passed
773
- a `callback(err, result)` which it must call on completion with an error `err`
774
- (which can be `null`) and an optional `result` value.
775
- * `callback(err, results)` - An optional callback to run once all the functions
776
- have completed. This function gets a results array (or object) containing all
777
- the result arguments passed to the task callbacks.
778
-
779
- __Example__
780
-
781
- ```js
782
- async.parallel([
783
- function(callback){
784
- setTimeout(function(){
785
- callback(null, 'one');
786
- }, 200);
787
- },
788
- function(callback){
789
- setTimeout(function(){
790
- callback(null, 'two');
791
- }, 100);
792
- }
793
- ],
794
- // optional callback
795
- function(err, results){
796
- // the results array will equal ['one','two'] even though
797
- // the second function had a shorter timeout.
798
- });
799
-
800
-
801
- // an example using an object instead of an array
802
- async.parallel({
803
- one: function(callback){
804
- setTimeout(function(){
805
- callback(null, 1);
806
- }, 200);
807
- },
808
- two: function(callback){
809
- setTimeout(function(){
810
- callback(null, 2);
811
- }, 100);
812
- }
813
- },
814
- function(err, results) {
815
- // results is now equals to: {one: 1, two: 2}
816
- });
817
- ```
818
-
819
- __Related__
820
-
821
- * parallelLimit(tasks, limit, [callback])
822
-
823
- ---------------------------------------
824
-
825
- <a name="whilst" />
826
- ### whilst(test, fn, callback)
827
-
828
- Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped,
829
- or an error occurs.
830
-
831
- __Arguments__
832
-
833
- * `test()` - synchronous truth test to perform before each execution of `fn`.
834
- * `fn(callback)` - A function which is called each time `test` passes. The function is
835
- passed a `callback(err)`, which must be called once it has completed with an
836
- optional `err` argument.
837
- * `callback(err)` - A callback which is called after the test fails and repeated
838
- execution of `fn` has stopped.
839
-
840
- __Example__
841
-
842
- ```js
843
- var count = 0;
844
-
845
- async.whilst(
846
- function () { return count < 5; },
847
- function (callback) {
848
- count++;
849
- setTimeout(callback, 1000);
850
- },
851
- function (err) {
852
- // 5 seconds have passed
853
- }
854
- );
855
- ```
856
-
857
- ---------------------------------------
858
-
859
- <a name="doWhilst" />
860
- ### doWhilst(fn, test, callback)
861
-
862
- The post-check version of [`whilst`](#whilst). To reflect the difference in
863
- the order of operations, the arguments `test` and `fn` are switched.
864
-
865
- `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
866
-
867
- ---------------------------------------
868
-
869
- <a name="until" />
870
- ### until(test, fn, callback)
871
-
872
- Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped,
873
- or an error occurs.
874
-
875
- The inverse of [`whilst`](#whilst).
876
-
877
- ---------------------------------------
878
-
879
- <a name="doUntil" />
880
- ### doUntil(fn, test, callback)
881
-
882
- Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`.
883
-
884
- ---------------------------------------
885
-
886
- <a name="during" />
887
- ### during(test, fn, callback)
888
-
889
- Like [`whilst`](#whilst), except the `test` is an asynchronous function that is passed a callback in the form of `function (err, truth)`. If error is passed to `test` or `fn`, the main callback is immediately called with the value of the error.
890
-
891
- __Example__
892
-
893
- ```js
894
- var count = 0;
895
-
896
- async.during(
897
- function (callback) {
898
- return callback(null, count < 5);
899
- },
900
- function (callback) {
901
- count++;
902
- setTimeout(callback, 1000);
903
- },
904
- function (err) {
905
- // 5 seconds have passed
906
- }
907
- );
908
- ```
909
-
910
- ---------------------------------------
911
-
912
- <a name="doDuring" />
913
- ### doDuring(fn, test, callback)
914
-
915
- The post-check version of [`during`](#during). To reflect the difference in
916
- the order of operations, the arguments `test` and `fn` are switched.
917
-
918
- Also a version of [`doWhilst`](#doWhilst) with asynchronous `test` function.
919
-
920
- ---------------------------------------
921
-
922
- <a name="forever" />
923
- ### forever(fn, [errback])
924
-
925
- Calls the asynchronous function `fn` with a callback parameter that allows it to
926
- call itself again, in series, indefinitely.
927
-
928
- If an error is passed to the callback then `errback` is called with the
929
- error, and execution stops, otherwise it will never be called.
930
-
931
- ```js
932
- async.forever(
933
- function(next) {
934
- // next is suitable for passing to things that need a callback(err [, whatever]);
935
- // it will result in this function being called again.
936
- },
937
- function(err) {
938
- // if next is called with a value in its first parameter, it will appear
939
- // in here as 'err', and execution will stop.
940
- }
941
- );
942
- ```
943
-
944
- ---------------------------------------
945
-
946
- <a name="waterfall" />
947
- ### waterfall(tasks, [callback])
948
-
949
- Runs the `tasks` array of functions in series, each passing their results to the next in
950
- the array. However, if any of the `tasks` pass an error to their own callback, the
951
- next function is not executed, and the main `callback` is immediately called with
952
- the error.
953
-
954
- __Arguments__
955
-
956
- * `tasks` - An array of functions to run, each function is passed a
957
- `callback(err, result1, result2, ...)` it must call on completion. The first
958
- argument is an error (which can be `null`) and any further arguments will be
959
- passed as arguments in order to the next task.
960
- * `callback(err, [results])` - An optional callback to run once all the functions
961
- have completed. This will be passed the results of the last task's callback.
962
-
963
-
964
-
965
- __Example__
966
-
967
- ```js
968
- async.waterfall([
969
- function(callback) {
970
- callback(null, 'one', 'two');
971
- },
972
- function(arg1, arg2, callback) {
973
- // arg1 now equals 'one' and arg2 now equals 'two'
974
- callback(null, 'three');
975
- },
976
- function(arg1, callback) {
977
- // arg1 now equals 'three'
978
- callback(null, 'done');
979
- }
980
- ], function (err, result) {
981
- // result now equals 'done'
982
- });
983
- ```
984
-
985
- ---------------------------------------
986
- <a name="compose" />
987
- ### compose(fn1, fn2...)
988
-
989
- Creates a function which is a composition of the passed asynchronous
990
- functions. Each function consumes the return value of the function that
991
- follows. Composing functions `f()`, `g()`, and `h()` would produce the result of
992
- `f(g(h()))`, only this version uses callbacks to obtain the return values.
993
-
994
- Each function is executed with the `this` binding of the composed function.
995
-
996
- __Arguments__
997
-
998
- * `functions...` - the asynchronous functions to compose
999
-
1000
-
1001
- __Example__
1002
-
1003
- ```js
1004
- function add1(n, callback) {
1005
- setTimeout(function () {
1006
- callback(null, n + 1);
1007
- }, 10);
1008
- }
1009
-
1010
- function mul3(n, callback) {
1011
- setTimeout(function () {
1012
- callback(null, n * 3);
1013
- }, 10);
1014
- }
1015
-
1016
- var add1mul3 = async.compose(mul3, add1);
1017
-
1018
- add1mul3(4, function (err, result) {
1019
- // result now equals 15
1020
- });
1021
- ```
1022
-
1023
- ---------------------------------------
1024
- <a name="seq" />
1025
- ### seq(fn1, fn2...)
1026
-
1027
- Version of the compose function that is more natural to read.
1028
- Each function consumes the return value of the previous function.
1029
- It is the equivalent of [`compose`](#compose) with the arguments reversed.
1030
-
1031
- Each function is executed with the `this` binding of the composed function.
1032
-
1033
- __Arguments__
1034
-
1035
- * `functions...` - the asynchronous functions to compose
1036
-
1037
-
1038
- __Example__
1039
-
1040
- ```js
1041
- // Requires lodash (or underscore), express3 and dresende's orm2.
1042
- // Part of an app, that fetches cats of the logged user.
1043
- // This example uses `seq` function to avoid overnesting and error
1044
- // handling clutter.
1045
- app.get('/cats', function(request, response) {
1046
- var User = request.models.User;
1047
- async.seq(
1048
- _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
1049
- function(user, fn) {
1050
- user.getCats(fn); // 'getCats' has signature (callback(err, data))
1051
- }
1052
- )(req.session.user_id, function (err, cats) {
1053
- if (err) {
1054
- console.error(err);
1055
- response.json({ status: 'error', message: err.message });
1056
- } else {
1057
- response.json({ status: 'ok', message: 'Cats found', data: cats });
1058
- }
1059
- });
1060
- });
1061
- ```
1062
-
1063
- ---------------------------------------
1064
- <a name="applyEach" />
1065
- ### applyEach(fns, args..., callback)
1066
-
1067
- Applies the provided arguments to each function in the array, calling
1068
- `callback` after all functions have completed. If you only provide the first
1069
- argument, then it will return a function which lets you pass in the
1070
- arguments as if it were a single function call.
1071
-
1072
- __Arguments__
1073
-
1074
- * `fns` - the asynchronous functions to all call with the same arguments
1075
- * `args...` - any number of separate arguments to pass to the function
1076
- * `callback` - the final argument should be the callback, called when all
1077
- functions have completed processing
1078
-
1079
-
1080
- __Example__
1081
-
1082
- ```js
1083
- async.applyEach([enableSearch, updateSchema], 'bucket', callback);
1084
-
1085
- // partial application example:
1086
- async.each(
1087
- buckets,
1088
- async.applyEach([enableSearch, updateSchema]),
1089
- callback
1090
- );
1091
- ```
1092
-
1093
- __Related__
1094
-
1095
- * applyEachSeries(tasks, args..., [callback])
1096
-
1097
- ---------------------------------------
1098
-
1099
- <a name="queue" />
1100
- ### queue(worker, [concurrency])
1101
-
1102
- Creates a `queue` object with the specified `concurrency`. Tasks added to the
1103
- `queue` are processed in parallel (up to the `concurrency` limit). If all
1104
- `worker`s are in progress, the task is queued until one becomes available.
1105
- Once a `worker` completes a `task`, that `task`'s callback is called.
1106
-
1107
- __Arguments__
1108
-
1109
- * `worker(task, callback)` - An asynchronous function for processing a queued
1110
- task, which must call its `callback(err)` argument when finished, with an
1111
- optional `error` as an argument. If you want to handle errors from an individual task, pass a callback to `q.push()`.
1112
- * `concurrency` - An `integer` for determining how many `worker` functions should be
1113
- run in parallel. If omitted, the concurrency defaults to `1`. If the concurrency is `0`, an error is thrown.
1114
-
1115
- __Queue objects__
1116
-
1117
- The `queue` object returned by this function has the following properties and
1118
- methods:
1119
-
1120
- * `length()` - a function returning the number of items waiting to be processed.
1121
- * `started` - a function returning whether or not any items have been pushed and processed by the queue
1122
- * `running()` - a function returning the number of items currently being processed.
1123
- * `idle()` - a function returning false if there are items waiting or being processed, or true if not.
1124
- * `concurrency` - an integer for determining how many `worker` functions should be
1125
- run in parallel. This property can be changed after a `queue` is created to
1126
- alter the concurrency on-the-fly.
1127
- * `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once
1128
- the `worker` has finished processing the task. Instead of a single task, a `tasks` array
1129
- can be submitted. The respective callback is used for every task in the list.
1130
- * `unshift(task, [callback])` - add a new task to the front of the `queue`.
1131
- * `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit,
1132
- and further tasks will be queued.
1133
- * `empty` - a callback that is called when the last item from the `queue` is given to a `worker`.
1134
- * `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`.
1135
- * `paused` - a boolean for determining whether the queue is in a paused state
1136
- * `pause()` - a function that pauses the processing of tasks until `resume()` is called.
1137
- * `resume()` - a function that resumes the processing of queued tasks when the queue is paused.
1138
- * `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle.
1139
-
1140
- __Example__
1141
-
1142
- ```js
1143
- // create a queue object with concurrency 2
1144
-
1145
- var q = async.queue(function (task, callback) {
1146
- console.log('hello ' + task.name);
1147
- callback();
1148
- }, 2);
1149
-
1150
-
1151
- // assign a callback
1152
- q.drain = function() {
1153
- console.log('all items have been processed');
1154
- }
1155
-
1156
- // add some items to the queue
1157
-
1158
- q.push({name: 'foo'}, function (err) {
1159
- console.log('finished processing foo');
1160
- });
1161
- q.push({name: 'bar'}, function (err) {
1162
- console.log('finished processing bar');
1163
- });
1164
-
1165
- // add some items to the queue (batch-wise)
1166
-
1167
- q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {
1168
- console.log('finished processing item');
1169
- });
1170
-
1171
- // add some items to the front of the queue
1172
-
1173
- q.unshift({name: 'bar'}, function (err) {
1174
- console.log('finished processing bar');
1175
- });
1176
- ```
1177
-
1178
-
1179
- ---------------------------------------
1180
-
1181
- <a name="priorityQueue" />
1182
- ### priorityQueue(worker, concurrency)
1183
-
1184
- The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects:
1185
-
1186
- * `push(task, priority, [callback])` - `priority` should be a number. If an array of
1187
- `tasks` is given, all tasks will be assigned the same priority.
1188
- * The `unshift` method was removed.
1189
-
1190
- ---------------------------------------
1191
-
1192
- <a name="cargo" />
1193
- ### cargo(worker, [payload])
1194
-
1195
- Creates a `cargo` object with the specified payload. Tasks added to the
1196
- cargo will be processed altogether (up to the `payload` limit). If the
1197
- `worker` is in progress, the task is queued until it becomes available. Once
1198
- the `worker` has completed some tasks, each callback of those tasks is called.
1199
- Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) for how `cargo` and `queue` work.
1200
-
1201
- While [queue](#queue) passes only one task to one of a group of workers
1202
- at a time, cargo passes an array of tasks to a single worker, repeating
1203
- when the worker is finished.
1204
-
1205
- __Arguments__
1206
-
1207
- * `worker(tasks, callback)` - An asynchronous function for processing an array of
1208
- queued tasks, which must call its `callback(err)` argument when finished, with
1209
- an optional `err` argument.
1210
- * `payload` - An optional `integer` for determining how many tasks should be
1211
- processed per round; if omitted, the default is unlimited.
1212
-
1213
- __Cargo objects__
1214
-
1215
- The `cargo` object returned by this function has the following properties and
1216
- methods:
1217
-
1218
- * `length()` - A function returning the number of items waiting to be processed.
1219
- * `payload` - An `integer` for determining how many tasks should be
1220
- process per round. This property can be changed after a `cargo` is created to
1221
- alter the payload on-the-fly.
1222
- * `push(task, [callback])` - Adds `task` to the `queue`. The callback is called
1223
- once the `worker` has finished processing the task. Instead of a single task, an array of `tasks`
1224
- can be submitted. The respective callback is used for every task in the list.
1225
- * `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued.
1226
- * `empty` - A callback that is called when the last item from the `queue` is given to a `worker`.
1227
- * `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`.
1228
- * `idle()`, `pause()`, `resume()`, `kill()` - cargo inherits all of the same methods and event calbacks as [`queue`](#queue)
1229
-
1230
- __Example__
1231
-
1232
- ```js
1233
- // create a cargo object with payload 2
1234
-
1235
- var cargo = async.cargo(function (tasks, callback) {
1236
- for(var i=0; i<tasks.length; i++){
1237
- console.log('hello ' + tasks[i].name);
1238
- }
1239
- callback();
1240
- }, 2);
1241
-
1242
-
1243
- // add some items
1244
-
1245
- cargo.push({name: 'foo'}, function (err) {
1246
- console.log('finished processing foo');
1247
- });
1248
- cargo.push({name: 'bar'}, function (err) {
1249
- console.log('finished processing bar');
1250
- });
1251
- cargo.push({name: 'baz'}, function (err) {
1252
- console.log('finished processing baz');
1253
- });
1254
- ```
1255
-
1256
- ---------------------------------------
1257
-
1258
- <a name="auto" />
1259
- ### auto(tasks, [callback])
1260
-
1261
- Determines the best order for running the functions in `tasks`, based on their requirements. Each function can optionally depend on other functions being completed first, and each function is run as soon as its requirements are satisfied.
1262
-
1263
- If any of the functions pass an error to their callback, the `auto` sequence will stop. Further tasks will not execute (so any other functions depending on it will not run), and the main `callback` is immediately called with the error. Functions also receive an object containing the results of functions which have completed so far.
1264
-
1265
- Note, all functions are called with a `results` object as a second argument,
1266
- so it is unsafe to pass functions in the `tasks` object which cannot handle the
1267
- extra argument.
1268
-
1269
- For example, this snippet of code:
1270
-
1271
- ```js
1272
- async.auto({
1273
- readData: async.apply(fs.readFile, 'data.txt', 'utf-8')
1274
- }, callback);
1275
- ```
1276
-
1277
- will have the effect of calling `readFile` with the results object as the last
1278
- argument, which will fail:
1279
-
1280
- ```js
1281
- fs.readFile('data.txt', 'utf-8', cb, {});
1282
- ```
1283
-
1284
- Instead, wrap the call to `readFile` in a function which does not forward the
1285
- `results` object:
1286
-
1287
- ```js
1288
- async.auto({
1289
- readData: function(cb, results){
1290
- fs.readFile('data.txt', 'utf-8', cb);
1291
- }
1292
- }, callback);
1293
- ```
1294
-
1295
- __Arguments__
1296
-
1297
- * `tasks` - An object. Each of its properties is either a function or an array of
1298
- requirements, with the function itself the last item in the array. The object's key
1299
- of a property serves as the name of the task defined by that property,
1300
- i.e. can be used when specifying requirements for other tasks.
1301
- The function receives two arguments: (1) a `callback(err, result)` which must be
1302
- called when finished, passing an `error` (which can be `null`) and the result of
1303
- the function's execution, and (2) a `results` object, containing the results of
1304
- the previously executed functions.
1305
- * `callback(err, results)` - An optional callback which is called when all the
1306
- tasks have been completed. It receives the `err` argument if any `tasks`
1307
- pass an error to their callback. Results are always returned; however, if
1308
- an error occurs, no further `tasks` will be performed, and the results
1309
- object will only contain partial results.
1310
-
1311
-
1312
- __Example__
1313
-
1314
- ```js
1315
- async.auto({
1316
- get_data: function(callback){
1317
- console.log('in get_data');
1318
- // async code to get some data
1319
- callback(null, 'data', 'converted to array');
1320
- },
1321
- make_folder: function(callback){
1322
- console.log('in make_folder');
1323
- // async code to create a directory to store a file in
1324
- // this is run at the same time as getting the data
1325
- callback(null, 'folder');
1326
- },
1327
- write_file: ['get_data', 'make_folder', function(callback, results){
1328
- console.log('in write_file', JSON.stringify(results));
1329
- // once there is some data and the directory exists,
1330
- // write the data to a file in the directory
1331
- callback(null, 'filename');
1332
- }],
1333
- email_link: ['write_file', function(callback, results){
1334
- console.log('in email_link', JSON.stringify(results));
1335
- // once the file is written let's email a link to it...
1336
- // results.write_file contains the filename returned by write_file.
1337
- callback(null, {'file':results.write_file, 'email':'user@example.com'});
1338
- }]
1339
- }, function(err, results) {
1340
- console.log('err = ', err);
1341
- console.log('results = ', results);
1342
- });
1343
- ```
1344
-
1345
- This is a fairly trivial example, but to do this using the basic parallel and
1346
- series functions would look like this:
1347
-
1348
- ```js
1349
- async.parallel([
1350
- function(callback){
1351
- console.log('in get_data');
1352
- // async code to get some data
1353
- callback(null, 'data', 'converted to array');
1354
- },
1355
- function(callback){
1356
- console.log('in make_folder');
1357
- // async code to create a directory to store a file in
1358
- // this is run at the same time as getting the data
1359
- callback(null, 'folder');
1360
- }
1361
- ],
1362
- function(err, results){
1363
- async.series([
1364
- function(callback){
1365
- console.log('in write_file', JSON.stringify(results));
1366
- // once there is some data and the directory exists,
1367
- // write the data to a file in the directory
1368
- results.push('filename');
1369
- callback(null);
1370
- },
1371
- function(callback){
1372
- console.log('in email_link', JSON.stringify(results));
1373
- // once the file is written let's email a link to it...
1374
- callback(null, {'file':results.pop(), 'email':'user@example.com'});
1375
- }
1376
- ]);
1377
- });
1378
- ```
1379
-
1380
- For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding
1381
- new tasks much easier (and the code more readable).
1382
-
1383
-
1384
- ---------------------------------------
1385
-
1386
- <a name="retry" />
1387
- ### retry([opts = {times: 5, interval: 0}| 5], task, [callback])
1388
-
1389
- Attempts to get a successful response from `task` no more than `times` times before
1390
- returning an error. If the task is successful, the `callback` will be passed the result
1391
- of the successful task. If all attempts fail, the callback will be passed the error and
1392
- result (if any) of the final attempt.
1393
-
1394
- __Arguments__
1395
-
1396
- * `opts` - Can be either an object with `times` and `interval` or a number. `times` is how many attempts should be made before giving up. `interval` is how long to wait inbetween attempts. Defaults to {times: 5, interval: 0}
1397
- * if a number is passed in it sets `times` only (with `interval` defaulting to 0).
1398
- * `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)`
1399
- which must be called when finished, passing `err` (which can be `null`) and the `result` of
1400
- the function's execution, and (2) a `results` object, containing the results of
1401
- the previously executed functions (if nested inside another control flow).
1402
- * `callback(err, results)` - An optional callback which is called when the
1403
- task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`.
1404
-
1405
- The [`retry`](#retry) function can be used as a stand-alone control flow by passing a
1406
- callback, as shown below:
1407
-
1408
- ```js
1409
- async.retry(3, apiMethod, function(err, result) {
1410
- // do something with the result
1411
- });
1412
- ```
1413
-
1414
- ```js
1415
- async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
1416
- // do something with the result
1417
- });
1418
- ```
1419
-
1420
- It can also be embeded within other control flow functions to retry individual methods
1421
- that are not as reliable, like this:
1422
-
1423
- ```js
1424
- async.auto({
1425
- users: api.getUsers.bind(api),
1426
- payments: async.retry(3, api.getPayments.bind(api))
1427
- }, function(err, results) {
1428
- // do something with the results
1429
- });
1430
- ```
1431
-
1432
-
1433
- ---------------------------------------
1434
-
1435
- <a name="iterator" />
1436
- ### iterator(tasks)
1437
-
1438
- Creates an iterator function which calls the next function in the `tasks` array,
1439
- returning a continuation to call the next one after that. It's also possible to
1440
- “peek” at the next iterator with `iterator.next()`.
1441
-
1442
- This function is used internally by the `async` module, but can be useful when
1443
- you want to manually control the flow of functions in series.
1444
-
1445
- __Arguments__
1446
-
1447
- * `tasks` - An array of functions to run.
1448
-
1449
- __Example__
1450
-
1451
- ```js
1452
- var iterator = async.iterator([
1453
- function(){ sys.p('one'); },
1454
- function(){ sys.p('two'); },
1455
- function(){ sys.p('three'); }
1456
- ]);
1457
-
1458
- node> var iterator2 = iterator();
1459
- 'one'
1460
- node> var iterator3 = iterator2();
1461
- 'two'
1462
- node> iterator3();
1463
- 'three'
1464
- node> var nextfn = iterator2.next();
1465
- node> nextfn();
1466
- 'three'
1467
- ```
1468
-
1469
- ---------------------------------------
1470
-
1471
- <a name="apply" />
1472
- ### apply(function, arguments..)
1473
-
1474
- Creates a continuation function with some arguments already applied.
1475
-
1476
- Useful as a shorthand when combined with other control flow functions. Any arguments
1477
- passed to the returned function are added to the arguments originally passed
1478
- to apply.
1479
-
1480
- __Arguments__
1481
-
1482
- * `function` - The function you want to eventually apply all arguments to.
1483
- * `arguments...` - Any number of arguments to automatically apply when the
1484
- continuation is called.
1485
-
1486
- __Example__
1487
-
1488
- ```js
1489
- // using apply
1490
-
1491
- async.parallel([
1492
- async.apply(fs.writeFile, 'testfile1', 'test1'),
1493
- async.apply(fs.writeFile, 'testfile2', 'test2'),
1494
- ]);
1495
-
1496
-
1497
- // the same process without using apply
1498
-
1499
- async.parallel([
1500
- function(callback){
1501
- fs.writeFile('testfile1', 'test1', callback);
1502
- },
1503
- function(callback){
1504
- fs.writeFile('testfile2', 'test2', callback);
1505
- }
1506
- ]);
1507
- ```
1508
-
1509
- It's possible to pass any number of additional arguments when calling the
1510
- continuation:
1511
-
1512
- ```js
1513
- node> var fn = async.apply(sys.puts, 'one');
1514
- node> fn('two', 'three');
1515
- one
1516
- two
1517
- three
1518
- ```
1519
-
1520
- ---------------------------------------
1521
-
1522
- <a name="nextTick" />
1523
- ### nextTick(callback), setImmediate(callback)
1524
-
1525
- Calls `callback` on a later loop around the event loop. In Node.js this just
1526
- calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)`
1527
- if available, otherwise `setTimeout(callback, 0)`, which means other higher priority
1528
- events may precede the execution of `callback`.
1529
-
1530
- This is used internally for browser-compatibility purposes.
1531
-
1532
- __Arguments__
1533
-
1534
- * `callback` - The function to call on a later loop around the event loop.
1535
-
1536
- __Example__
1537
-
1538
- ```js
1539
- var call_order = [];
1540
- async.nextTick(function(){
1541
- call_order.push('two');
1542
- // call_order now equals ['one','two']
1543
- });
1544
- call_order.push('one')
1545
- ```
1546
-
1547
- <a name="times" />
1548
- ### times(n, iterator, [callback])
1549
-
1550
- Calls the `iterator` function `n` times, and accumulates results in the same manner
1551
- you would use with [`map`](#map).
1552
-
1553
- __Arguments__
1554
-
1555
- * `n` - The number of times to run the function.
1556
- * `iterator` - The function to call `n` times.
1557
- * `callback` - see [`map`](#map)
1558
-
1559
- __Example__
1560
-
1561
- ```js
1562
- // Pretend this is some complicated async factory
1563
- var createUser = function(id, callback) {
1564
- callback(null, {
1565
- id: 'user' + id
1566
- })
1567
- }
1568
- // generate 5 users
1569
- async.times(5, function(n, next){
1570
- createUser(n, function(err, user) {
1571
- next(err, user)
1572
- })
1573
- }, function(err, users) {
1574
- // we should now have 5 users
1575
- });
1576
- ```
1577
-
1578
- __Related__
1579
-
1580
- * timesSeries(n, iterator, [callback])
1581
- * timesLimit(n, limit, iterator, [callback])
1582
-
1583
-
1584
- ## Utils
1585
-
1586
- <a name="memoize" />
1587
- ### memoize(fn, [hasher])
1588
-
1589
- Caches the results of an `async` function. When creating a hash to store function
1590
- results against, the callback is omitted from the hash and an optional hash
1591
- function can be used.
1592
-
1593
- If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function.
1594
-
1595
- The cache of results is exposed as the `memo` property of the function returned
1596
- by `memoize`.
1597
-
1598
- __Arguments__
1599
-
1600
- * `fn` - The function to proxy and cache results from.
1601
- * `hasher` - An optional function for generating a custom hash for storing
1602
- results. It has all the arguments applied to it apart from the callback, and
1603
- must be synchronous.
1604
-
1605
- __Example__
1606
-
1607
- ```js
1608
- var slow_fn = function (name, callback) {
1609
- // do something
1610
- callback(null, result);
1611
- };
1612
- var fn = async.memoize(slow_fn);
1613
-
1614
- // fn can now be used as if it were slow_fn
1615
- fn('some name', function () {
1616
- // callback
1617
- });
1618
- ```
1619
-
1620
- <a name="unmemoize" />
1621
- ### unmemoize(fn)
1622
-
1623
- Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized
1624
- form. Handy for testing.
1625
-
1626
- __Arguments__
1627
-
1628
- * `fn` - the memoized function
1629
-
1630
- ---------------------------------------
1631
-
1632
- <a name="ensureAsync" />
1633
- ### ensureAsync(fn)
1634
-
1635
- Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (`RangeError: Maximum call stack size exceeded`) and generally keeping [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) contained.
1636
-
1637
- __Arguments__
1638
-
1639
- * `fn` - an async function, one that expects a node-style callback as its last argument
1640
-
1641
- Returns a wrapped function with the exact same call signature as the function passed in.
1642
-
1643
- __Example__
1644
-
1645
- ```js
1646
- function sometimesAsync(arg, callback) {
1647
- if (cache[arg]) {
1648
- return callback(null, cache[arg]); // this would be synchronous!!
1649
- } else {
1650
- doSomeIO(arg, callback); // this IO would be asynchronous
1651
- }
1652
- }
1653
-
1654
- // this has a risk of stack overflows if many results are cached in a row
1655
- async.mapSeries(args, sometimesAsync, done);
1656
-
1657
- // this will defer sometimesAsync's callback if necessary,
1658
- // preventing stack overflows
1659
- async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
1660
-
1661
- ```
1662
-
1663
- ---------------------------------------
1664
-
1665
- <a name="constant">
1666
- ### constant(values...)
1667
-
1668
- Returns a function that when called, calls-back with the values provided. Useful as the first function in a `waterfall`, or for plugging values in to `auto`.
1669
-
1670
- __Example__
1671
-
1672
- ```js
1673
- async.waterfall([
1674
- async.constant(42),
1675
- function (value, next) {
1676
- // value === 42
1677
- },
1678
- //...
1679
- ], callback);
1680
-
1681
- async.waterfall([
1682
- async.constant(filename, "utf8"),
1683
- fs.readFile,
1684
- function (fileData, next) {
1685
- //...
1686
- }
1687
- //...
1688
- ], callback);
1689
-
1690
- async.auto({
1691
- hostname: async.constant("https://server.net/"),
1692
- port: findFreePort,
1693
- launchServer: ["hostname", "port", function (cb, options) {
1694
- startServer(options, cb);
1695
- }],
1696
- //...
1697
- }, callback);
1698
-
1699
- ```
1700
-
1701
- ---------------------------------------
1702
-
1703
- <a name="asyncify">
1704
- <a name="wrapSync">
1705
- ### asyncify(func)
1706
-
1707
- __Alias:__ `wrapSync`
1708
-
1709
- Take a sync function and make it async, passing its return value to a callback. This is useful for plugging sync functions into a waterfall, series, or other async functions. Any arguments passed to the generated function will be passed to the wrapped function (except for the final callback argument). Errors thrown will be passed to the callback.
1710
-
1711
- __Example__
1712
-
1713
- ```js
1714
- async.waterfall([
1715
- async.apply(fs.readFile, filename, "utf8"),
1716
- async.asyncify(JSON.parse),
1717
- function (data, next) {
1718
- // data is the result of parsing the text.
1719
- // If there was a parsing error, it would have been caught.
1720
- }
1721
- ], callback)
1722
- ```
1723
-
1724
- ---------------------------------------
1725
-
1726
- <a name="log" />
1727
- ### log(function, arguments)
1728
-
1729
- Logs the result of an `async` function to the `console`. Only works in Node.js or
1730
- in browsers that support `console.log` and `console.error` (such as FF and Chrome).
1731
- If multiple arguments are returned from the async function, `console.log` is
1732
- called on each argument in order.
1733
-
1734
- __Arguments__
1735
-
1736
- * `function` - The function you want to eventually apply all arguments to.
1737
- * `arguments...` - Any number of arguments to apply to the function.
1738
-
1739
- __Example__
1740
-
1741
- ```js
1742
- var hello = function(name, callback){
1743
- setTimeout(function(){
1744
- callback(null, 'hello ' + name);
1745
- }, 1000);
1746
- };
1747
- ```
1748
- ```js
1749
- node> async.log(hello, 'world');
1750
- 'hello world'
1751
- ```
1752
-
1753
- ---------------------------------------
1754
-
1755
- <a name="dir" />
1756
- ### dir(function, arguments)
1757
-
1758
- Logs the result of an `async` function to the `console` using `console.dir` to
1759
- display the properties of the resulting object. Only works in Node.js or
1760
- in browsers that support `console.dir` and `console.error` (such as FF and Chrome).
1761
- If multiple arguments are returned from the async function, `console.dir` is
1762
- called on each argument in order.
1763
-
1764
- __Arguments__
1765
-
1766
- * `function` - The function you want to eventually apply all arguments to.
1767
- * `arguments...` - Any number of arguments to apply to the function.
1768
-
1769
- __Example__
1770
-
1771
- ```js
1772
- var hello = function(name, callback){
1773
- setTimeout(function(){
1774
- callback(null, {hello: name});
1775
- }, 1000);
1776
- };
1777
- ```
1778
- ```js
1779
- node> async.dir(hello, 'world');
1780
- {hello: 'world'}
1781
- ```
1782
-
1783
- ---------------------------------------
1784
-
1785
- <a name="noConflict" />
1786
- ### noConflict()
1787
-
1788
- Changes the value of `async` back to its original value, returning a reference to the
1789
- `async` object.