step.js 993 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. (function(define){
  3. define(function(require,exports){
  4. // Vladimir Dronnikov
  5. // inspired by creationix's Step
  6. var when = require('./promise').when;
  7. // execute sequentially functions taken from steps[]
  8. // each successive is fed with the result of prior
  9. // each function can return an immediate value, a promise, or just throw
  10. // in the latter case the next function will receive Error object
  11. // return "undefined" to full stop.
  12. //
  13. // "context" is available to each steps as "this"
  14. //
  15. exports.Step = function(context, steps) {
  16. var next;
  17. next = function() {
  18. var fn, result;
  19. if (!steps.length) {
  20. return arguments[0];
  21. }
  22. fn = steps.shift();
  23. try {
  24. result = fn.apply(context, arguments);
  25. if (result !== void 0) {
  26. result = when(result, next, next);
  27. }
  28. } catch (err) {
  29. next(err);
  30. }
  31. return result;
  32. };
  33. return next();
  34. };
  35. });
  36. })(typeof define!="undefined"?define:function(factory){factory(require,exports)});