2015-11-03 01:39:42 +03:00
|
|
|
/**
|
|
|
|
* # Pipeline Utility
|
|
|
|
*
|
|
|
|
* Based on pipeline.js from when.js:
|
|
|
|
* https://github.com/cujojs/when/blob/3.7.4/pipeline.js
|
|
|
|
*/
|
2014-08-17 10:17:23 +04:00
|
|
|
var Promise = require('bluebird');
|
|
|
|
|
|
|
|
function pipeline(tasks /* initial arguments */) {
|
|
|
|
var args = Array.prototype.slice.call(arguments, 1),
|
|
|
|
|
|
|
|
runTask = function (task, args) {
|
2015-11-03 01:39:42 +03:00
|
|
|
// Self-optimizing function to run first task with multiple
|
|
|
|
// args using apply, but subsequent tasks via direct invocation
|
2014-08-17 10:17:23 +04:00
|
|
|
runTask = function (task, arg) {
|
|
|
|
return task(arg);
|
|
|
|
};
|
|
|
|
|
|
|
|
return task.apply(null, args);
|
|
|
|
};
|
|
|
|
|
2015-11-03 01:39:42 +03:00
|
|
|
// Resolve any promises for the arguments passed in first
|
|
|
|
return Promise.all(args).then(function (args) {
|
|
|
|
// Iterate through the tasks passing args from one into the next
|
|
|
|
return Promise.reduce(tasks, function (arg, task) {
|
|
|
|
return runTask(task, arg);
|
|
|
|
}, args);
|
|
|
|
});
|
2014-08-17 10:17:23 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = pipeline;
|