UNPKG

1.22 kBJavaScriptView Raw
1/** @license MIT License (c) copyright 2011-2013 original author or authors */
2
3/**
4 * sequence.js
5 *
6 * Run a set of task functions in sequence. All tasks will
7 * receive the same args.
8 *
9 * @author Brian Cavalier
10 * @author John Hann
11 */
12
13(function(define) {
14define(function(require) {
15
16 var when = require('./when');
17 var all = when.Promise.all;
18 var slice = Array.prototype.slice;
19
20 /**
21 * Run array of tasks in sequence with no overlap
22 * @param tasks {Array|Promise} array or promiseForArray of task functions
23 * @param [args] {*} arguments to be passed to all tasks
24 * @return {Promise} promise for an array containing
25 * the result of each task in the array position corresponding
26 * to position of the task in the tasks array
27 */
28 return function sequence(tasks /*, args... */) {
29 var results = [];
30
31 return all(slice.call(arguments, 1)).then(function(args) {
32 return when.reduce(tasks, function(results, task) {
33 return when(task.apply(void 0, args), addResult);
34 }, results);
35 });
36
37 function addResult(result) {
38 results.push(result);
39 return results;
40 }
41 };
42
43});
44})(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
45
46