ensureAsync.js 2.3 KB

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