README.md
1# a-sync-waterfall
2
3Simple, isolated sync/async waterfall module for JavaScript.
4
5Runs an array of functions in series, each passing their results to the next in
6the array. However, if any of the functions pass an error to the callback, the
7next function is not executed and the main callback is immediately called with
8the error.
9
10For browsers and node.js.
11
12## Installation
13* Just include a-sync-waterfall before your scripts.
14* `npm install a-sync-waterfall` if you’re using node.js.
15
16
17## Usage
18
19* `waterfall(tasks, optionalCallback, forceAsync);`
20* **tasks** - An array of functions to run, each function is passed a
21`callback(err, result1, result2, ...)` it must call on completion. The first
22argument is an error (which can be null) and any further arguments will be
23passed as arguments in order to the next task.
24* **optionalCallback** - An optional callback to run once all the functions have
25completed. This will be passed the results of the last task's callback.
26* **forceAsync** An optional flag that force tasks run asynchronously even if they are sync.
27
28##### Node.js:
29
30```javascript
31var waterfall = require('a-sync-waterfall');
32waterfall(tasks, callback);
33```
34
35##### Browser:
36
37```javascript
38var waterfall = require('a-sync-waterfall');
39waterfall(tasks, callback);
40
41// Default:
42window.waterfall(tasks, callback);
43```
44
45##### Tasks as Array of Functions
46
47```javascript
48waterfall([
49 function(callback){
50 callback(null, 'one', 'two');
51 },
52 function(arg1, arg2, callback){
53 callback(null, 'three');
54 },
55 function(arg1, callback){
56 // arg1 now equals 'three'
57 callback(null, 'done');
58 }
59], function (err, result) {
60 // result now equals 'done'
61});
62```
63
64##### Derive Tasks from an Array.map
65
66```javascript
67/* basic - no arguments */
68waterfall(myArray.map(function (arrayItem) {
69 return function (nextCallback) {
70 // same execution for each item, call the next one when done
71 doAsyncThingsWith(arrayItem, nextCallback);
72}}));
73
74/* with arguments, initializer function, and final callback */
75waterfall([function initializer (firstMapFunction) {
76 firstMapFunction(null, initialValue);
77 }].concat(myArray.map(function (arrayItem) {
78 return function (lastItemResult, nextCallback) {
79 // same execution for each item in the array
80 var itemResult = doThingsWith(arrayItem, lastItemResult);
81 // results carried along from each to the next
82 nextCallback(null, itemResult);
83}})), function (err, finalResult) {
84 // final callback
85});
86```
87
88## Acknowledgements
89Hat tip to [Caolan McMahon](https://github.com/caolan) and
90[Paul Miller](https://github.com/paulmillr), whose prior contributions this is
91based upon.
92Also [Elan Shanker](https://github.com/es128) from which this rep is forked
93
94## License
95[MIT](https://raw.github.com/hydiak/a-sync-waterfall/master/LICENSE)
96