'use strict';12Object.defineProperty(exports, "__esModule", {3value: true4});5exports.default = ensureAsync;67var _setImmediate = require('./internal/setImmediate.js');89var _setImmediate2 = _interopRequireDefault(_setImmediate);1011var _wrapAsync = require('./internal/wrapAsync.js');1213function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }1415/**16* Wrap an async function and ensure it calls its callback on a later tick of17* the event loop. If the function already calls its callback on a next tick,18* no extra deferral is added. This is useful for preventing stack overflows19* (`RangeError: Maximum call stack size exceeded`) and generally keeping20* [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)21* contained. ES2017 `async` functions are returned as-is -- they are immune22* to Zalgo's corrupting influences, as they always resolve on a later tick.23*24* @name ensureAsync25* @static26* @memberOf module:Utils27* @method28* @category Util29* @param {AsyncFunction} fn - an async function, one that expects a node-style30* callback as its last argument.31* @returns {AsyncFunction} Returns a wrapped function with the exact same call32* signature as the function passed in.33* @example34*35* function sometimesAsync(arg, callback) {36* if (cache[arg]) {37* return callback(null, cache[arg]); // this would be synchronous!!38* } else {39* doSomeIO(arg, callback); // this IO would be asynchronous40* }41* }42*43* // this has a risk of stack overflows if many results are cached in a row44* async.mapSeries(args, sometimesAsync, done);45*46* // this will defer sometimesAsync's callback if necessary,47* // preventing stack overflows48* async.mapSeries(args, async.ensureAsync(sometimesAsync), done);49*/50function ensureAsync(fn) {51if ((0, _wrapAsync.isAsync)(fn)) return fn;52return function (...args /*, callback*/) {53var callback = args.pop();54var sync = true;55args.push((...innerArgs) => {56if (sync) {57(0, _setImmediate2.default)(() => callback(...innerArgs));58} else {59callback(...innerArgs);60}61});62fn.apply(this, args);63sync = false;64};65}66module.exports = exports['default'];6768