1 | /** @license MIT License (c) copyright 2011-2013 original author or authors */
|
2 |
|
3 | /**
|
4 | * pipeline.js
|
5 | *
|
6 | * Run a set of task functions in sequence, passing the result
|
7 | * of the previous as an argument to the next. Like a shell
|
8 | * pipeline, e.g. `cat file.txt | grep 'foo' | sed -e 's/foo/bar/g'
|
9 | *
|
10 | * @author Brian Cavalier
|
11 | * @author John Hann
|
12 | */
|
13 |
|
14 | (function(define) {
|
15 | define(function(require) {
|
16 |
|
17 | var when = require('./when');
|
18 | var all = when.Promise.all;
|
19 | var slice = Array.prototype.slice;
|
20 |
|
21 | /**
|
22 | * Run array of tasks in a pipeline where the next
|
23 | * tasks receives the result of the previous. The first task
|
24 | * will receive the initialArgs as its argument list.
|
25 | * @param tasks {Array|Promise} array or promise for array of task functions
|
26 | * @param [initialArgs...] {*} arguments to be passed to the first task
|
27 | * @return {Promise} promise for return value of the final task
|
28 | */
|
29 | return function pipeline(tasks /* initialArgs... */) {
|
30 | // Self-optimizing function to run first task with multiple
|
31 | // args using apply, but subsequence tasks via direct invocation
|
32 | var runTask = function(args, task) {
|
33 | runTask = function(arg, task) {
|
34 | return task(arg);
|
35 | };
|
36 |
|
37 | return task.apply(null, args);
|
38 | };
|
39 |
|
40 | return all(slice.call(arguments, 1)).then(function(args) {
|
41 | return when.reduce(tasks, function(arg, task) {
|
42 | return runTask(arg, task);
|
43 | }, args);
|
44 | });
|
45 | };
|
46 |
|
47 | });
|
48 | })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
|
49 |
|
50 |
|