apply.js

  1. import slice from './internal/slice';
  2. /**
  3. * Creates a continuation function with some arguments already applied.
  4. *
  5. * Useful as a shorthand when combined with other control flow functions. Any
  6. * arguments passed to the returned function are added to the arguments
  7. * originally passed to apply.
  8. *
  9. * @name apply
  10. * @static
  11. * @memberOf module:Utils
  12. * @method
  13. * @category Util
  14. * @param {Function} fn - The function you want to eventually apply all
  15. * arguments to. Invokes with (arguments...).
  16. * @param {...*} arguments... - Any number of arguments to automatically apply
  17. * when the continuation is called.
  18. * @returns {Function} the partially-applied function
  19. * @example
  20. *
  21. * // using apply
  22. * async.parallel([
  23. * async.apply(fs.writeFile, 'testfile1', 'test1'),
  24. * async.apply(fs.writeFile, 'testfile2', 'test2')
  25. * ]);
  26. *
  27. *
  28. * // the same process without using apply
  29. * async.parallel([
  30. * function(callback) {
  31. * fs.writeFile('testfile1', 'test1', callback);
  32. * },
  33. * function(callback) {
  34. * fs.writeFile('testfile2', 'test2', callback);
  35. * }
  36. * ]);
  37. *
  38. * // It's possible to pass any number of additional arguments when calling the
  39. * // continuation:
  40. *
  41. * node> var fn = async.apply(sys.puts, 'one');
  42. * node> fn('two', 'three');
  43. * one
  44. * two
  45. * three
  46. */
  47. export default function(fn/*, ...args*/) {
  48. var args = slice(arguments, 1);
  49. return function(/*callArgs*/) {
  50. var callArgs = slice(arguments);
  51. return fn.apply(null, args.concat(callArgs));
  52. };
  53. };