summaryrefslogtreecommitdiff
path: root/lib/iterator.js
blob: b37c18a677b9d87d0fea982f8129ed5121cef349 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
 * Creates an iterator function which calls the next function in the `tasks`
 * array, returning a continuation to call the next one after that. It's also
 * possible to “peek” at the next iterator with `iterator.next()`.
 *
 * This function is used internally by the `async` module, but can be useful
 * when you want to manually control the flow of functions in series.
 *
 * @name iterator
 * @static
 * @memberOf async
 * @category Control Flow
 * @param {Array} tasks - An array of functions to run.
 * @returns The next function to run in the series.
 * @example
 *
 * var iterator = async.iterator([
 *     function() { sys.p('one'); },
 *     function() { sys.p('two'); },
 *     function() { sys.p('three'); }
 * ]);
 *
 * node> var iterator2 = iterator();
 * 'one'
 * node> var iterator3 = iterator2();
 * 'two'
 * node> iterator3();
 * 'three'
 * node> var nextfn = iterator2.next();
 * node> nextfn();
 * 'three'
 */
export default function(tasks) {
    function makeCallback(index) {
        function fn() {
            if (tasks.length) {
                tasks[index].apply(null, arguments);
            }
            return fn.next();
        }
        fn.next = function() {
            return (index < tasks.length - 1) ? makeCallback(index + 1) : null;
        };
        return fn;
    }
    return makeCallback(0);
}