ensureAsync.js 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = ensureAsync;
  6. var _setImmediate = require('./internal/setImmediate');
  7. var _setImmediate2 = _interopRequireDefault(_setImmediate);
  8. var _initialParams = require('./internal/initialParams');
  9. var _initialParams2 = _interopRequireDefault(_initialParams);
  10. var _wrapAsync = require('./internal/wrapAsync');
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. /**
  13. * Wrap an async function and ensure it calls its callback on a later tick of
  14. * the event loop. If the function already calls its callback on a next tick,
  15. * no extra deferral is added. This is useful for preventing stack overflows
  16. * (`RangeError: Maximum call stack size exceeded`) and generally keeping
  17. * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
  18. * contained. ES2017 `async` functions are returned as-is -- they are immune
  19. * to Zalgo's corrupting influences, as they always resolve on a later tick.
  20. *
  21. * @name ensureAsync
  22. * @static
  23. * @memberOf module:Utils
  24. * @method
  25. * @category Util
  26. * @param {AsyncFunction} fn - an async function, one that expects a node-style
  27. * callback as its last argument.
  28. * @returns {AsyncFunction} Returns a wrapped function with the exact same call
  29. * signature as the function passed in.
  30. * @example
  31. *
  32. * function sometimesAsync(arg, callback) {
  33. * if (cache[arg]) {
  34. * return callback(null, cache[arg]); // this would be synchronous!!
  35. * } else {
  36. * doSomeIO(arg, callback); // this IO would be asynchronous
  37. * }
  38. * }
  39. *
  40. * // this has a risk of stack overflows if many results are cached in a row
  41. * async.mapSeries(args, sometimesAsync, done);
  42. *
  43. * // this will defer sometimesAsync's callback if necessary,
  44. * // preventing stack overflows
  45. * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
  46. */
  47. function ensureAsync(fn) {
  48. if ((0, _wrapAsync.isAsync)(fn)) return fn;
  49. return (0, _initialParams2.default)(function (args, callback) {
  50. var sync = true;
  51. args.push(function () {
  52. var innerArgs = arguments;
  53. if (sync) {
  54. (0, _setImmediate2.default)(function () {
  55. callback.apply(null, innerArgs);
  56. });
  57. } else {
  58. callback.apply(null, innerArgs);
  59. }
  60. });
  61. fn.apply(this, args);
  62. sync = false;
  63. });
  64. }
  65. module.exports = exports['default'];