seq.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = seq;
  6. var _reduce = require('./reduce.js');
  7. var _reduce2 = _interopRequireDefault(_reduce);
  8. var _wrapAsync = require('./internal/wrapAsync.js');
  9. var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
  10. var _promiseCallback = require('./internal/promiseCallback.js');
  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 {...AsyncFunction} 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. * User.get.bind(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. function seq(...functions) {
  51. var _functions = functions.map(_wrapAsync2.default);
  52. return function (...args) {
  53. var that = this;
  54. var cb = args[args.length - 1];
  55. if (typeof cb == 'function') {
  56. args.pop();
  57. } else {
  58. cb = (0, _promiseCallback.promiseCallback)();
  59. }
  60. (0, _reduce2.default)(_functions, args, (newargs, fn, iterCb) => {
  61. fn.apply(that, newargs.concat((err, ...nextargs) => {
  62. iterCb(err, nextargs);
  63. }));
  64. }, (err, results) => cb(err, ...results));
  65. return cb[_promiseCallback.PROMISE_SYMBOL];
  66. };
  67. }
  68. module.exports = exports['default'];