sequence.js 1.2 KB

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