seq.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _noop = require('lodash/noop');
  6. var _noop2 = _interopRequireDefault(_noop);
  7. var _rest = require('./internal/rest');
  8. var _rest2 = _interopRequireDefault(_rest);
  9. var _reduce = require('./reduce');
  10. var _reduce2 = _interopRequireDefault(_reduce);
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. /**
  13. * Version of the compose function that is more natural to read. Each function
  14. * consumes the return value of the previous function. It is the equivalent of
  15. * [compose]{@link module:ControlFlow.compose} with the arguments reversed.
  16. *
  17. * Each function is executed with the `this` binding of the composed function.
  18. *
  19. * @name seq
  20. * @static
  21. * @memberOf module:ControlFlow
  22. * @method
  23. * @see [async.compose]{@link module:ControlFlow.compose}
  24. * @category Control Flow
  25. * @param {...Function} functions - the asynchronous functions to compose
  26. * @returns {Function} a function that composes the `functions` in order
  27. * @example
  28. *
  29. * // Requires lodash (or underscore), express3 and dresende's orm2.
  30. * // Part of an app, that fetches cats of the logged user.
  31. * // This example uses `seq` function to avoid overnesting and error
  32. * // handling clutter.
  33. * app.get('/cats', function(request, response) {
  34. * var User = request.models.User;
  35. * async.seq(
  36. * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
  37. * function(user, fn) {
  38. * user.getCats(fn); // 'getCats' has signature (callback(err, data))
  39. * }
  40. * )(req.session.user_id, function (err, cats) {
  41. * if (err) {
  42. * console.error(err);
  43. * response.json({ status: 'error', message: err.message });
  44. * } else {
  45. * response.json({ status: 'ok', message: 'Cats found', data: cats });
  46. * }
  47. * });
  48. * });
  49. */
  50. exports.default = (0, _rest2.default)(function seq(functions) {
  51. return (0, _rest2.default)(function (args) {
  52. var that = this;
  53. var cb = args[args.length - 1];
  54. if (typeof cb == 'function') {
  55. args.pop();
  56. } else {
  57. cb = _noop2.default;
  58. }
  59. (0, _reduce2.default)(functions, args, function (newargs, fn, cb) {
  60. fn.apply(that, newargs.concat([(0, _rest2.default)(function (err, nextargs) {
  61. cb(err, nextargs);
  62. })]));
  63. }, function (err, results) {
  64. cb.apply(that, [err].concat(results));
  65. });
  66. });
  67. });
  68. module.exports = exports['default'];