/**1* Creates a continuation function with some arguments already applied.2*3* Useful as a shorthand when combined with other control flow functions. Any4* arguments passed to the returned function are added to the arguments5* originally passed to apply.6*7* @name apply8* @static9* @memberOf module:Utils10* @method11* @category Util12* @param {Function} fn - The function you want to eventually apply all13* arguments to. Invokes with (arguments...).14* @param {...*} arguments... - Any number of arguments to automatically apply15* when the continuation is called.16* @returns {Function} the partially-applied function17* @example18*19* // using apply20* async.parallel([21* async.apply(fs.writeFile, 'testfile1', 'test1'),22* async.apply(fs.writeFile, 'testfile2', 'test2')23* ]);24*25*26* // the same process without using apply27* async.parallel([28* function(callback) {29* fs.writeFile('testfile1', 'test1', callback);30* },31* function(callback) {32* fs.writeFile('testfile2', 'test2', callback);33* }34* ]);35*36* // It's possible to pass any number of additional arguments when calling the37* // continuation:38*39* node> var fn = async.apply(sys.puts, 'one');40* node> fn('two', 'three');41* one42* two43* three44*/45function apply(fn, ...args) {46return (...callArgs) => fn(...args,...callArgs);47}4849function initialParams (fn) {50return function (...args/*, callback*/) {51var callback = args.pop();52return fn.call(this, args, callback);53};54}5556/* istanbul ignore file */5758var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;59var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;60var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';6162function fallback(fn) {63setTimeout(fn, 0);64}6566function wrap(defer) {67return (fn, ...args) => defer(() => fn(...args));68}6970var _defer;7172if (hasQueueMicrotask) {73_defer = queueMicrotask;74} else if (hasSetImmediate) {75_defer = setImmediate;76} else if (hasNextTick) {77_defer = process.nextTick;78} else {79_defer = fallback;80}8182var setImmediate$1 = wrap(_defer);8384/**85* Take a sync function and make it async, passing its return value to a86* callback. This is useful for plugging sync functions into a waterfall,87* series, or other async functions. Any arguments passed to the generated88* function will be passed to the wrapped function (except for the final89* callback argument). Errors thrown will be passed to the callback.90*91* If the function passed to `asyncify` returns a Promise, that promises's92* resolved/rejected state will be used to call the callback, rather than simply93* the synchronous return value.94*95* This also means you can asyncify ES2017 `async` functions.96*97* @name asyncify98* @static99* @memberOf module:Utils100* @method101* @alias wrapSync102* @category Util103* @param {Function} func - The synchronous function, or Promise-returning104* function to convert to an {@link AsyncFunction}.105* @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be106* invoked with `(args..., callback)`.107* @example108*109* // passing a regular synchronous function110* async.waterfall([111* async.apply(fs.readFile, filename, "utf8"),112* async.asyncify(JSON.parse),113* function (data, next) {114* // data is the result of parsing the text.115* // If there was a parsing error, it would have been caught.116* }117* ], callback);118*119* // passing a function returning a promise120* async.waterfall([121* async.apply(fs.readFile, filename, "utf8"),122* async.asyncify(function (contents) {123* return db.model.create(contents);124* }),125* function (model, next) {126* // `model` is the instantiated model object.127* // If there was an error, this function would be skipped.128* }129* ], callback);130*131* // es2017 example, though `asyncify` is not needed if your JS environment132* // supports async functions out of the box133* var q = async.queue(async.asyncify(async function(file) {134* var intermediateStep = await processFile(file);135* return await somePromise(intermediateStep)136* }));137*138* q.push(files);139*/140function asyncify(func) {141if (isAsync(func)) {142return function (...args/*, callback*/) {143const callback = args.pop();144const promise = func.apply(this, args);145return handlePromise(promise, callback)146}147}148149return initialParams(function (args, callback) {150var result;151try {152result = func.apply(this, args);153} catch (e) {154return callback(e);155}156// if result is Promise object157if (result && typeof result.then === 'function') {158return handlePromise(result, callback)159} else {160callback(null, result);161}162});163}164165function handlePromise(promise, callback) {166return promise.then(value => {167invokeCallback(callback, null, value);168}, err => {169invokeCallback(callback, err && err.message ? err : new Error(err));170});171}172173function invokeCallback(callback, error, value) {174try {175callback(error, value);176} catch (err) {177setImmediate$1(e => { throw e }, err);178}179}180181function isAsync(fn) {182return fn[Symbol.toStringTag] === 'AsyncFunction';183}184185function isAsyncGenerator(fn) {186return fn[Symbol.toStringTag] === 'AsyncGenerator';187}188189function isAsyncIterable(obj) {190return typeof obj[Symbol.asyncIterator] === 'function';191}192193function wrapAsync(asyncFn) {194if (typeof asyncFn !== 'function') throw new Error('expected a function')195return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;196}197198// conditionally promisify a function.199// only return a promise if a callback is omitted200function awaitify (asyncFn, arity = asyncFn.length) {201if (!arity) throw new Error('arity is undefined')202function awaitable (...args) {203if (typeof args[arity - 1] === 'function') {204return asyncFn.apply(this, args)205}206207return new Promise((resolve, reject) => {208args[arity - 1] = (err, ...cbArgs) => {209if (err) return reject(err)210resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);211};212asyncFn.apply(this, args);213})214}215216return awaitable217}218219function applyEach (eachfn) {220return function applyEach(fns, ...callArgs) {221const go = awaitify(function (callback) {222var that = this;223return eachfn(fns, (fn, cb) => {224wrapAsync(fn).apply(that, callArgs.concat(cb));225}, callback);226});227return go;228};229}230231function _asyncMap(eachfn, arr, iteratee, callback) {232arr = arr || [];233var results = [];234var counter = 0;235var _iteratee = wrapAsync(iteratee);236237return eachfn(arr, (value, _, iterCb) => {238var index = counter++;239_iteratee(value, (err, v) => {240results[index] = v;241iterCb(err);242});243}, err => {244callback(err, results);245});246}247248function isArrayLike(value) {249return value &&250typeof value.length === 'number' &&251value.length >= 0 &&252value.length % 1 === 0;253}254255// A temporary value used to identify if the loop should be broken.256// See #1064, #1293257const breakLoop = {};258259function once(fn) {260function wrapper (...args) {261if (fn === null) return;262var callFn = fn;263fn = null;264callFn.apply(this, args);265}266Object.assign(wrapper, fn);267return wrapper268}269270function getIterator (coll) {271return coll[Symbol.iterator] && coll[Symbol.iterator]();272}273274function createArrayIterator(coll) {275var i = -1;276var len = coll.length;277return function next() {278return ++i < len ? {value: coll[i], key: i} : null;279}280}281282function createES2015Iterator(iterator) {283var i = -1;284return function next() {285var item = iterator.next();286if (item.done)287return null;288i++;289return {value: item.value, key: i};290}291}292293function createObjectIterator(obj) {294var okeys = obj ? Object.keys(obj) : [];295var i = -1;296var len = okeys.length;297return function next() {298var key = okeys[++i];299if (key === '__proto__') {300return next();301}302return i < len ? {value: obj[key], key} : null;303};304}305306function createIterator(coll) {307if (isArrayLike(coll)) {308return createArrayIterator(coll);309}310311var iterator = getIterator(coll);312return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);313}314315function onlyOnce(fn) {316return function (...args) {317if (fn === null) throw new Error("Callback was already called.");318var callFn = fn;319fn = null;320callFn.apply(this, args);321};322}323324// for async generators325function asyncEachOfLimit(generator, limit, iteratee, callback) {326let done = false;327let canceled = false;328let awaiting = false;329let running = 0;330let idx = 0;331332function replenish() {333//console.log('replenish')334if (running >= limit || awaiting || done) return335//console.log('replenish awaiting')336awaiting = true;337generator.next().then(({value, done: iterDone}) => {338//console.log('got value', value)339if (canceled || done) return340awaiting = false;341if (iterDone) {342done = true;343if (running <= 0) {344//console.log('done nextCb')345callback(null);346}347return;348}349running++;350iteratee(value, idx, iterateeCallback);351idx++;352replenish();353}).catch(handleError);354}355356function iterateeCallback(err, result) {357//console.log('iterateeCallback')358running -= 1;359if (canceled) return360if (err) return handleError(err)361362if (err === false) {363done = true;364canceled = true;365return366}367368if (result === breakLoop || (done && running <= 0)) {369done = true;370//console.log('done iterCb')371return callback(null);372}373replenish();374}375376function handleError(err) {377if (canceled) return378awaiting = false;379done = true;380callback(err);381}382383replenish();384}385386var eachOfLimit = (limit) => {387return (obj, iteratee, callback) => {388callback = once(callback);389if (limit <= 0) {390throw new RangeError('concurrency limit cannot be less than 1')391}392if (!obj) {393return callback(null);394}395if (isAsyncGenerator(obj)) {396return asyncEachOfLimit(obj, limit, iteratee, callback)397}398if (isAsyncIterable(obj)) {399return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback)400}401var nextElem = createIterator(obj);402var done = false;403var canceled = false;404var running = 0;405var looping = false;406407function iterateeCallback(err, value) {408if (canceled) return409running -= 1;410if (err) {411done = true;412callback(err);413}414else if (err === false) {415done = true;416canceled = true;417}418else if (value === breakLoop || (done && running <= 0)) {419done = true;420return callback(null);421}422else if (!looping) {423replenish();424}425}426427function replenish () {428looping = true;429while (running < limit && !done) {430var elem = nextElem();431if (elem === null) {432done = true;433if (running <= 0) {434callback(null);435}436return;437}438running += 1;439iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));440}441looping = false;442}443444replenish();445};446};447448/**449* The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a450* time.451*452* @name eachOfLimit453* @static454* @memberOf module:Collections455* @method456* @see [async.eachOf]{@link module:Collections.eachOf}457* @alias forEachOfLimit458* @category Collection459* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.460* @param {number} limit - The maximum number of async operations at a time.461* @param {AsyncFunction} iteratee - An async function to apply to each462* item in `coll`. The `key` is the item's key, or index in the case of an463* array.464* Invoked with (item, key, callback).465* @param {Function} [callback] - A callback which is called when all466* `iteratee` functions have finished, or an error occurs. Invoked with (err).467* @returns {Promise} a promise, if a callback is omitted468*/469function eachOfLimit$1(coll, limit, iteratee, callback) {470return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);471}472473var eachOfLimit$2 = awaitify(eachOfLimit$1, 4);474475// eachOf implementation optimized for array-likes476function eachOfArrayLike(coll, iteratee, callback) {477callback = once(callback);478var index = 0,479completed = 0,480{length} = coll,481canceled = false;482if (length === 0) {483callback(null);484}485486function iteratorCallback(err, value) {487if (err === false) {488canceled = true;489}490if (canceled === true) return491if (err) {492callback(err);493} else if ((++completed === length) || value === breakLoop) {494callback(null);495}496}497498for (; index < length; index++) {499iteratee(coll[index], index, onlyOnce(iteratorCallback));500}501}502503// a generic version of eachOf which can handle array, object, and iterator cases.504function eachOfGeneric (coll, iteratee, callback) {505return eachOfLimit$2(coll, Infinity, iteratee, callback);506}507508/**509* Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument510* to the iteratee.511*512* @name eachOf513* @static514* @memberOf module:Collections515* @method516* @alias forEachOf517* @category Collection518* @see [async.each]{@link module:Collections.each}519* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.520* @param {AsyncFunction} iteratee - A function to apply to each521* item in `coll`.522* The `key` is the item's key, or index in the case of an array.523* Invoked with (item, key, callback).524* @param {Function} [callback] - A callback which is called when all525* `iteratee` functions have finished, or an error occurs. Invoked with (err).526* @returns {Promise} a promise, if a callback is omitted527* @example528*529* // dev.json is a file containing a valid json object config for dev environment530* // dev.json is a file containing a valid json object config for test environment531* // prod.json is a file containing a valid json object config for prod environment532* // invalid.json is a file with a malformed json object533*534* let configs = {}; //global variable535* let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};536* let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};537*538* // asynchronous function that reads a json file and parses the contents as json object539* function parseFile(file, key, callback) {540* fs.readFile(file, "utf8", function(err, data) {541* if (err) return calback(err);542* try {543* configs[key] = JSON.parse(data);544* } catch (e) {545* return callback(e);546* }547* callback();548* });549* }550*551* // Using callbacks552* async.forEachOf(validConfigFileMap, parseFile, function (err) {553* if (err) {554* console.error(err);555* } else {556* console.log(configs);557* // configs is now a map of JSON data, e.g.558* // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}559* }560* });561*562* //Error handing563* async.forEachOf(invalidConfigFileMap, parseFile, function (err) {564* if (err) {565* console.error(err);566* // JSON parse error exception567* } else {568* console.log(configs);569* }570* });571*572* // Using Promises573* async.forEachOf(validConfigFileMap, parseFile)574* .then( () => {575* console.log(configs);576* // configs is now a map of JSON data, e.g.577* // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}578* }).catch( err => {579* console.error(err);580* });581*582* //Error handing583* async.forEachOf(invalidConfigFileMap, parseFile)584* .then( () => {585* console.log(configs);586* }).catch( err => {587* console.error(err);588* // JSON parse error exception589* });590*591* // Using async/await592* async () => {593* try {594* let result = await async.forEachOf(validConfigFileMap, parseFile);595* console.log(configs);596* // configs is now a map of JSON data, e.g.597* // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}598* }599* catch (err) {600* console.log(err);601* }602* }603*604* //Error handing605* async () => {606* try {607* let result = await async.forEachOf(invalidConfigFileMap, parseFile);608* console.log(configs);609* }610* catch (err) {611* console.log(err);612* // JSON parse error exception613* }614* }615*616*/617function eachOf(coll, iteratee, callback) {618var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;619return eachOfImplementation(coll, wrapAsync(iteratee), callback);620}621622var eachOf$1 = awaitify(eachOf, 3);623624/**625* Produces a new collection of values by mapping each value in `coll` through626* the `iteratee` function. The `iteratee` is called with an item from `coll`627* and a callback for when it has finished processing. Each of these callbacks628* takes 2 arguments: an `error`, and the transformed item from `coll`. If629* `iteratee` passes an error to its callback, the main `callback` (for the630* `map` function) is immediately called with the error.631*632* Note, that since this function applies the `iteratee` to each item in633* parallel, there is no guarantee that the `iteratee` functions will complete634* in order. However, the results array will be in the same order as the635* original `coll`.636*637* If `map` is passed an Object, the results will be an Array. The results638* will roughly be in the order of the original Objects' keys (but this can639* vary across JavaScript engines).640*641* @name map642* @static643* @memberOf module:Collections644* @method645* @category Collection646* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.647* @param {AsyncFunction} iteratee - An async function to apply to each item in648* `coll`.649* The iteratee should complete with the transformed item.650* Invoked with (item, callback).651* @param {Function} [callback] - A callback which is called when all `iteratee`652* functions have finished, or an error occurs. Results is an Array of the653* transformed items from the `coll`. Invoked with (err, results).654* @returns {Promise} a promise, if no callback is passed655* @example656*657* // file1.txt is a file that is 1000 bytes in size658* // file2.txt is a file that is 2000 bytes in size659* // file3.txt is a file that is 3000 bytes in size660* // file4.txt does not exist661*662* const fileList = ['file1.txt','file2.txt','file3.txt'];663* const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];664*665* // asynchronous function that returns the file size in bytes666* function getFileSizeInBytes(file, callback) {667* fs.stat(file, function(err, stat) {668* if (err) {669* return callback(err);670* }671* callback(null, stat.size);672* });673* }674*675* // Using callbacks676* async.map(fileList, getFileSizeInBytes, function(err, results) {677* if (err) {678* console.log(err);679* } else {680* console.log(results);681* // results is now an array of the file size in bytes for each file, e.g.682* // [ 1000, 2000, 3000]683* }684* });685*686* // Error Handling687* async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {688* if (err) {689* console.log(err);690* // [ Error: ENOENT: no such file or directory ]691* } else {692* console.log(results);693* }694* });695*696* // Using Promises697* async.map(fileList, getFileSizeInBytes)698* .then( results => {699* console.log(results);700* // results is now an array of the file size in bytes for each file, e.g.701* // [ 1000, 2000, 3000]702* }).catch( err => {703* console.log(err);704* });705*706* // Error Handling707* async.map(withMissingFileList, getFileSizeInBytes)708* .then( results => {709* console.log(results);710* }).catch( err => {711* console.log(err);712* // [ Error: ENOENT: no such file or directory ]713* });714*715* // Using async/await716* async () => {717* try {718* let results = await async.map(fileList, getFileSizeInBytes);719* console.log(results);720* // results is now an array of the file size in bytes for each file, e.g.721* // [ 1000, 2000, 3000]722* }723* catch (err) {724* console.log(err);725* }726* }727*728* // Error Handling729* async () => {730* try {731* let results = await async.map(withMissingFileList, getFileSizeInBytes);732* console.log(results);733* }734* catch (err) {735* console.log(err);736* // [ Error: ENOENT: no such file or directory ]737* }738* }739*740*/741function map (coll, iteratee, callback) {742return _asyncMap(eachOf$1, coll, iteratee, callback)743}744var map$1 = awaitify(map, 3);745746/**747* Applies the provided arguments to each function in the array, calling748* `callback` after all functions have completed. If you only provide the first749* argument, `fns`, then it will return a function which lets you pass in the750* arguments as if it were a single function call. If more arguments are751* provided, `callback` is required while `args` is still optional. The results752* for each of the applied async functions are passed to the final callback753* as an array.754*755* @name applyEach756* @static757* @memberOf module:ControlFlow758* @method759* @category Control Flow760* @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s761* to all call with the same arguments762* @param {...*} [args] - any number of separate arguments to pass to the763* function.764* @param {Function} [callback] - the final argument should be the callback,765* called when all functions have completed processing.766* @returns {AsyncFunction} - Returns a function that takes no args other than767* an optional callback, that is the result of applying the `args` to each768* of the functions.769* @example770*771* const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket')772*773* appliedFn((err, results) => {774* // results[0] is the results for `enableSearch`775* // results[1] is the results for `updateSchema`776* });777*778* // partial application example:779* async.each(780* buckets,781* async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(),782* callback783* );784*/785var applyEach$1 = applyEach(map$1);786787/**788* The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.789*790* @name eachOfSeries791* @static792* @memberOf module:Collections793* @method794* @see [async.eachOf]{@link module:Collections.eachOf}795* @alias forEachOfSeries796* @category Collection797* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.798* @param {AsyncFunction} iteratee - An async function to apply to each item in799* `coll`.800* Invoked with (item, key, callback).801* @param {Function} [callback] - A callback which is called when all `iteratee`802* functions have finished, or an error occurs. Invoked with (err).803* @returns {Promise} a promise, if a callback is omitted804*/805function eachOfSeries(coll, iteratee, callback) {806return eachOfLimit$2(coll, 1, iteratee, callback)807}808var eachOfSeries$1 = awaitify(eachOfSeries, 3);809810/**811* The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.812*813* @name mapSeries814* @static815* @memberOf module:Collections816* @method817* @see [async.map]{@link module:Collections.map}818* @category Collection819* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.820* @param {AsyncFunction} iteratee - An async function to apply to each item in821* `coll`.822* The iteratee should complete with the transformed item.823* Invoked with (item, callback).824* @param {Function} [callback] - A callback which is called when all `iteratee`825* functions have finished, or an error occurs. Results is an array of the826* transformed items from the `coll`. Invoked with (err, results).827* @returns {Promise} a promise, if no callback is passed828*/829function mapSeries (coll, iteratee, callback) {830return _asyncMap(eachOfSeries$1, coll, iteratee, callback)831}832var mapSeries$1 = awaitify(mapSeries, 3);833834/**835* The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.836*837* @name applyEachSeries838* @static839* @memberOf module:ControlFlow840* @method841* @see [async.applyEach]{@link module:ControlFlow.applyEach}842* @category Control Flow843* @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all844* call with the same arguments845* @param {...*} [args] - any number of separate arguments to pass to the846* function.847* @param {Function} [callback] - the final argument should be the callback,848* called when all functions have completed processing.849* @returns {AsyncFunction} - A function, that when called, is the result of850* appling the `args` to the list of functions. It takes no args, other than851* a callback.852*/853var applyEachSeries = applyEach(mapSeries$1);854855const PROMISE_SYMBOL = Symbol('promiseCallback');856857function promiseCallback () {858let resolve, reject;859function callback (err, ...args) {860if (err) return reject(err)861resolve(args.length > 1 ? args : args[0]);862}863864callback[PROMISE_SYMBOL] = new Promise((res, rej) => {865resolve = res,866reject = rej;867});868869return callback870}871872/**873* Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on874* their requirements. Each function can optionally depend on other functions875* being completed first, and each function is run as soon as its requirements876* are satisfied.877*878* If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence879* will stop. Further tasks will not execute (so any other functions depending880* on it will not run), and the main `callback` is immediately called with the881* error.882*883* {@link AsyncFunction}s also receive an object containing the results of functions which884* have completed so far as the first argument, if they have dependencies. If a885* task function has no dependencies, it will only be passed a callback.886*887* @name auto888* @static889* @memberOf module:ControlFlow890* @method891* @category Control Flow892* @param {Object} tasks - An object. Each of its properties is either a893* function or an array of requirements, with the {@link AsyncFunction} itself the last item894* in the array. The object's key of a property serves as the name of the task895* defined by that property, i.e. can be used when specifying requirements for896* other tasks. The function receives one or two arguments:897* * a `results` object, containing the results of the previously executed898* functions, only passed if the task has any dependencies,899* * a `callback(err, result)` function, which must be called when finished,900* passing an `error` (which can be `null`) and the result of the function's901* execution.902* @param {number} [concurrency=Infinity] - An optional `integer` for903* determining the maximum number of tasks that can be run in parallel. By904* default, as many as possible.905* @param {Function} [callback] - An optional callback which is called when all906* the tasks have been completed. It receives the `err` argument if any `tasks`907* pass an error to their callback. Results are always returned; however, if an908* error occurs, no further `tasks` will be performed, and the results object909* will only contain partial results. Invoked with (err, results).910* @returns {Promise} a promise, if a callback is not passed911* @example912*913* //Using Callbacks914* async.auto({915* get_data: function(callback) {916* // async code to get some data917* callback(null, 'data', 'converted to array');918* },919* make_folder: function(callback) {920* // async code to create a directory to store a file in921* // this is run at the same time as getting the data922* callback(null, 'folder');923* },924* write_file: ['get_data', 'make_folder', function(results, callback) {925* // once there is some data and the directory exists,926* // write the data to a file in the directory927* callback(null, 'filename');928* }],929* email_link: ['write_file', function(results, callback) {930* // once the file is written let's email a link to it...931* callback(null, {'file':results.write_file, 'email':'[email protected]'});932* }]933* }, function(err, results) {934* if (err) {935* console.log('err = ', err);936* }937* console.log('results = ', results);938* // results = {939* // get_data: ['data', 'converted to array']940* // make_folder; 'folder',941* // write_file: 'filename'942* // email_link: { file: 'filename', email: '[email protected]' }943* // }944* });945*946* //Using Promises947* async.auto({948* get_data: function(callback) {949* console.log('in get_data');950* // async code to get some data951* callback(null, 'data', 'converted to array');952* },953* make_folder: function(callback) {954* console.log('in make_folder');955* // async code to create a directory to store a file in956* // this is run at the same time as getting the data957* callback(null, 'folder');958* },959* write_file: ['get_data', 'make_folder', function(results, callback) {960* // once there is some data and the directory exists,961* // write the data to a file in the directory962* callback(null, 'filename');963* }],964* email_link: ['write_file', function(results, callback) {965* // once the file is written let's email a link to it...966* callback(null, {'file':results.write_file, 'email':'[email protected]'});967* }]968* }).then(results => {969* console.log('results = ', results);970* // results = {971* // get_data: ['data', 'converted to array']972* // make_folder; 'folder',973* // write_file: 'filename'974* // email_link: { file: 'filename', email: '[email protected]' }975* // }976* }).catch(err => {977* console.log('err = ', err);978* });979*980* //Using async/await981* async () => {982* try {983* let results = await async.auto({984* get_data: function(callback) {985* // async code to get some data986* callback(null, 'data', 'converted to array');987* },988* make_folder: function(callback) {989* // async code to create a directory to store a file in990* // this is run at the same time as getting the data991* callback(null, 'folder');992* },993* write_file: ['get_data', 'make_folder', function(results, callback) {994* // once there is some data and the directory exists,995* // write the data to a file in the directory996* callback(null, 'filename');997* }],998* email_link: ['write_file', function(results, callback) {999* // once the file is written let's email a link to it...1000* callback(null, {'file':results.write_file, 'email':'[email protected]'});1001* }]1002* });1003* console.log('results = ', results);1004* // results = {1005* // get_data: ['data', 'converted to array']1006* // make_folder; 'folder',1007* // write_file: 'filename'1008* // email_link: { file: 'filename', email: '[email protected]' }1009* // }1010* }1011* catch (err) {1012* console.log(err);1013* }1014* }1015*1016*/1017function auto(tasks, concurrency, callback) {1018if (typeof concurrency !== 'number') {1019// concurrency is optional, shift the args.1020callback = concurrency;1021concurrency = null;1022}1023callback = once(callback || promiseCallback());1024var numTasks = Object.keys(tasks).length;1025if (!numTasks) {1026return callback(null);1027}1028if (!concurrency) {1029concurrency = numTasks;1030}10311032var results = {};1033var runningTasks = 0;1034var canceled = false;1035var hasError = false;10361037var listeners = Object.create(null);10381039var readyTasks = [];10401041// for cycle detection:1042var readyToCheck = []; // tasks that have been identified as reachable1043// without the possibility of returning to an ancestor task1044var uncheckedDependencies = {};10451046Object.keys(tasks).forEach(key => {1047var task = tasks[key];1048if (!Array.isArray(task)) {1049// no dependencies1050enqueueTask(key, [task]);1051readyToCheck.push(key);1052return;1053}10541055var dependencies = task.slice(0, task.length - 1);1056var remainingDependencies = dependencies.length;1057if (remainingDependencies === 0) {1058enqueueTask(key, task);1059readyToCheck.push(key);1060return;1061}1062uncheckedDependencies[key] = remainingDependencies;10631064dependencies.forEach(dependencyName => {1065if (!tasks[dependencyName]) {1066throw new Error('async.auto task `' + key +1067'` has a non-existent dependency `' +1068dependencyName + '` in ' +1069dependencies.join(', '));1070}1071addListener(dependencyName, () => {1072remainingDependencies--;1073if (remainingDependencies === 0) {1074enqueueTask(key, task);1075}1076});1077});1078});10791080checkForDeadlocks();1081processQueue();10821083function enqueueTask(key, task) {1084readyTasks.push(() => runTask(key, task));1085}10861087function processQueue() {1088if (canceled) return1089if (readyTasks.length === 0 && runningTasks === 0) {1090return callback(null, results);1091}1092while(readyTasks.length && runningTasks < concurrency) {1093var run = readyTasks.shift();1094run();1095}10961097}10981099function addListener(taskName, fn) {1100var taskListeners = listeners[taskName];1101if (!taskListeners) {1102taskListeners = listeners[taskName] = [];1103}11041105taskListeners.push(fn);1106}11071108function taskComplete(taskName) {1109var taskListeners = listeners[taskName] || [];1110taskListeners.forEach(fn => fn());1111processQueue();1112}111311141115function runTask(key, task) {1116if (hasError) return;11171118var taskCallback = onlyOnce((err, ...result) => {1119runningTasks--;1120if (err === false) {1121canceled = true;1122return1123}1124if (result.length < 2) {1125[result] = result;1126}1127if (err) {1128var safeResults = {};1129Object.keys(results).forEach(rkey => {1130safeResults[rkey] = results[rkey];1131});1132safeResults[key] = result;1133hasError = true;1134listeners = Object.create(null);1135if (canceled) return1136callback(err, safeResults);1137} else {1138results[key] = result;1139taskComplete(key);1140}1141});11421143runningTasks++;1144var taskFn = wrapAsync(task[task.length - 1]);1145if (task.length > 1) {1146taskFn(results, taskCallback);1147} else {1148taskFn(taskCallback);1149}1150}11511152function checkForDeadlocks() {1153// Kahn's algorithm1154// https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm1155// http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html1156var currentTask;1157var counter = 0;1158while (readyToCheck.length) {1159currentTask = readyToCheck.pop();1160counter++;1161getDependents(currentTask).forEach(dependent => {1162if (--uncheckedDependencies[dependent] === 0) {1163readyToCheck.push(dependent);1164}1165});1166}11671168if (counter !== numTasks) {1169throw new Error(1170'async.auto cannot execute tasks due to a recursive dependency'1171);1172}1173}11741175function getDependents(taskName) {1176var result = [];1177Object.keys(tasks).forEach(key => {1178const task = tasks[key];1179if (Array.isArray(task) && task.indexOf(taskName) >= 0) {1180result.push(key);1181}1182});1183return result;1184}11851186return callback[PROMISE_SYMBOL]1187}11881189var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/;1190var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/;1191var FN_ARG_SPLIT = /,/;1192var FN_ARG = /(=.+)?(\s*)$/;11931194function stripComments(string) {1195let stripped = '';1196let index = 0;1197let endBlockComment = string.indexOf('*/');1198while (index < string.length) {1199if (string[index] === '/' && string[index+1] === '/') {1200// inline comment1201let endIndex = string.indexOf('\n', index);1202index = (endIndex === -1) ? string.length : endIndex;1203} else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) {1204// block comment1205let endIndex = string.indexOf('*/', index);1206if (endIndex !== -1) {1207index = endIndex + 2;1208endBlockComment = string.indexOf('*/', index);1209} else {1210stripped += string[index];1211index++;1212}1213} else {1214stripped += string[index];1215index++;1216}1217}1218return stripped;1219}12201221function parseParams(func) {1222const src = stripComments(func.toString());1223let match = src.match(FN_ARGS);1224if (!match) {1225match = src.match(ARROW_FN_ARGS);1226}1227if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src)1228let [, args] = match;1229return args1230.replace(/\s/g, '')1231.split(FN_ARG_SPLIT)1232.map((arg) => arg.replace(FN_ARG, '').trim());1233}12341235/**1236* A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent1237* tasks are specified as parameters to the function, after the usual callback1238* parameter, with the parameter names matching the names of the tasks it1239* depends on. This can provide even more readable task graphs which can be1240* easier to maintain.1241*1242* If a final callback is specified, the task results are similarly injected,1243* specified as named parameters after the initial error parameter.1244*1245* The autoInject function is purely syntactic sugar and its semantics are1246* otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.1247*1248* @name autoInject1249* @static1250* @memberOf module:ControlFlow1251* @method1252* @see [async.auto]{@link module:ControlFlow.auto}1253* @category Control Flow1254* @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of1255* the form 'func([dependencies...], callback). The object's key of a property1256* serves as the name of the task defined by that property, i.e. can be used1257* when specifying requirements for other tasks.1258* * The `callback` parameter is a `callback(err, result)` which must be called1259* when finished, passing an `error` (which can be `null`) and the result of1260* the function's execution. The remaining parameters name other tasks on1261* which the task is dependent, and the results from those tasks are the1262* arguments of those parameters.1263* @param {Function} [callback] - An optional callback which is called when all1264* the tasks have been completed. It receives the `err` argument if any `tasks`1265* pass an error to their callback, and a `results` object with any completed1266* task results, similar to `auto`.1267* @returns {Promise} a promise, if no callback is passed1268* @example1269*1270* // The example from `auto` can be rewritten as follows:1271* async.autoInject({1272* get_data: function(callback) {1273* // async code to get some data1274* callback(null, 'data', 'converted to array');1275* },1276* make_folder: function(callback) {1277* // async code to create a directory to store a file in1278* // this is run at the same time as getting the data1279* callback(null, 'folder');1280* },1281* write_file: function(get_data, make_folder, callback) {1282* // once there is some data and the directory exists,1283* // write the data to a file in the directory1284* callback(null, 'filename');1285* },1286* email_link: function(write_file, callback) {1287* // once the file is written let's email a link to it...1288* // write_file contains the filename returned by write_file.1289* callback(null, {'file':write_file, 'email':'[email protected]'});1290* }1291* }, function(err, results) {1292* console.log('err = ', err);1293* console.log('email_link = ', results.email_link);1294* });1295*1296* // If you are using a JS minifier that mangles parameter names, `autoInject`1297* // will not work with plain functions, since the parameter names will be1298* // collapsed to a single letter identifier. To work around this, you can1299* // explicitly specify the names of the parameters your task function needs1300* // in an array, similar to Angular.js dependency injection.1301*1302* // This still has an advantage over plain `auto`, since the results a task1303* // depends on are still spread into arguments.1304* async.autoInject({1305* //...1306* write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {1307* callback(null, 'filename');1308* }],1309* email_link: ['write_file', function(write_file, callback) {1310* callback(null, {'file':write_file, 'email':'[email protected]'});1311* }]1312* //...1313* }, function(err, results) {1314* console.log('err = ', err);1315* console.log('email_link = ', results.email_link);1316* });1317*/1318function autoInject(tasks, callback) {1319var newTasks = {};13201321Object.keys(tasks).forEach(key => {1322var taskFn = tasks[key];1323var params;1324var fnIsAsync = isAsync(taskFn);1325var hasNoDeps =1326(!fnIsAsync && taskFn.length === 1) ||1327(fnIsAsync && taskFn.length === 0);13281329if (Array.isArray(taskFn)) {1330params = [...taskFn];1331taskFn = params.pop();13321333newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);1334} else if (hasNoDeps) {1335// no dependencies, use the function as-is1336newTasks[key] = taskFn;1337} else {1338params = parseParams(taskFn);1339if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) {1340throw new Error("autoInject task functions require explicit parameters.");1341}13421343// remove callback param1344if (!fnIsAsync) params.pop();13451346newTasks[key] = params.concat(newTask);1347}13481349function newTask(results, taskCb) {1350var newArgs = params.map(name => results[name]);1351newArgs.push(taskCb);1352wrapAsync(taskFn)(...newArgs);1353}1354});13551356return auto(newTasks, callback);1357}13581359// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation1360// used for queues. This implementation assumes that the node provided by the user can be modified1361// to adjust the next and last properties. We implement only the minimal functionality1362// for queue support.1363class DLL {1364constructor() {1365this.head = this.tail = null;1366this.length = 0;1367}13681369removeLink(node) {1370if (node.prev) node.prev.next = node.next;1371else this.head = node.next;1372if (node.next) node.next.prev = node.prev;1373else this.tail = node.prev;13741375node.prev = node.next = null;1376this.length -= 1;1377return node;1378}13791380empty () {1381while(this.head) this.shift();1382return this;1383}13841385insertAfter(node, newNode) {1386newNode.prev = node;1387newNode.next = node.next;1388if (node.next) node.next.prev = newNode;1389else this.tail = newNode;1390node.next = newNode;1391this.length += 1;1392}13931394insertBefore(node, newNode) {1395newNode.prev = node.prev;1396newNode.next = node;1397if (node.prev) node.prev.next = newNode;1398else this.head = newNode;1399node.prev = newNode;1400this.length += 1;1401}14021403unshift(node) {1404if (this.head) this.insertBefore(this.head, node);1405else setInitial(this, node);1406}14071408push(node) {1409if (this.tail) this.insertAfter(this.tail, node);1410else setInitial(this, node);1411}14121413shift() {1414return this.head && this.removeLink(this.head);1415}14161417pop() {1418return this.tail && this.removeLink(this.tail);1419}14201421toArray() {1422return [...this]1423}14241425*[Symbol.iterator] () {1426var cur = this.head;1427while (cur) {1428yield cur.data;1429cur = cur.next;1430}1431}14321433remove (testFn) {1434var curr = this.head;1435while(curr) {1436var {next} = curr;1437if (testFn(curr)) {1438this.removeLink(curr);1439}1440curr = next;1441}1442return this;1443}1444}14451446function setInitial(dll, node) {1447dll.length = 1;1448dll.head = dll.tail = node;1449}14501451function queue(worker, concurrency, payload) {1452if (concurrency == null) {1453concurrency = 1;1454}1455else if(concurrency === 0) {1456throw new RangeError('Concurrency must not be zero');1457}14581459var _worker = wrapAsync(worker);1460var numRunning = 0;1461var workersList = [];1462const events = {1463error: [],1464drain: [],1465saturated: [],1466unsaturated: [],1467empty: []1468};14691470function on (event, handler) {1471events[event].push(handler);1472}14731474function once (event, handler) {1475const handleAndRemove = (...args) => {1476off(event, handleAndRemove);1477handler(...args);1478};1479events[event].push(handleAndRemove);1480}14811482function off (event, handler) {1483if (!event) return Object.keys(events).forEach(ev => events[ev] = [])1484if (!handler) return events[event] = []1485events[event] = events[event].filter(ev => ev !== handler);1486}14871488function trigger (event, ...args) {1489events[event].forEach(handler => handler(...args));1490}14911492var processingScheduled = false;1493function _insert(data, insertAtFront, rejectOnError, callback) {1494if (callback != null && typeof callback !== 'function') {1495throw new Error('task callback must be a function');1496}1497q.started = true;14981499var res, rej;1500function promiseCallback (err, ...args) {1501// we don't care about the error, let the global error handler1502// deal with it1503if (err) return rejectOnError ? rej(err) : res()1504if (args.length <= 1) return res(args[0])1505res(args);1506}15071508var item = q._createTaskItem(1509data,1510rejectOnError ? promiseCallback :1511(callback || promiseCallback)1512);15131514if (insertAtFront) {1515q._tasks.unshift(item);1516} else {1517q._tasks.push(item);1518}15191520if (!processingScheduled) {1521processingScheduled = true;1522setImmediate$1(() => {1523processingScheduled = false;1524q.process();1525});1526}15271528if (rejectOnError || !callback) {1529return new Promise((resolve, reject) => {1530res = resolve;1531rej = reject;1532})1533}1534}15351536function _createCB(tasks) {1537return function (err, ...args) {1538numRunning -= 1;15391540for (var i = 0, l = tasks.length; i < l; i++) {1541var task = tasks[i];15421543var index = workersList.indexOf(task);1544if (index === 0) {1545workersList.shift();1546} else if (index > 0) {1547workersList.splice(index, 1);1548}15491550task.callback(err, ...args);15511552if (err != null) {1553trigger('error', err, task.data);1554}1555}15561557if (numRunning <= (q.concurrency - q.buffer) ) {1558trigger('unsaturated');1559}15601561if (q.idle()) {1562trigger('drain');1563}1564q.process();1565};1566}15671568function _maybeDrain(data) {1569if (data.length === 0 && q.idle()) {1570// call drain immediately if there are no tasks1571setImmediate$1(() => trigger('drain'));1572return true1573}1574return false1575}15761577const eventMethod = (name) => (handler) => {1578if (!handler) {1579return new Promise((resolve, reject) => {1580once(name, (err, data) => {1581if (err) return reject(err)1582resolve(data);1583});1584})1585}1586off(name);1587on(name, handler);15881589};15901591var isProcessing = false;1592var q = {1593_tasks: new DLL(),1594_createTaskItem (data, callback) {1595return {1596data,1597callback1598};1599},1600*[Symbol.iterator] () {1601yield* q._tasks[Symbol.iterator]();1602},1603concurrency,1604payload,1605buffer: concurrency / 4,1606started: false,1607paused: false,1608push (data, callback) {1609if (Array.isArray(data)) {1610if (_maybeDrain(data)) return1611return data.map(datum => _insert(datum, false, false, callback))1612}1613return _insert(data, false, false, callback);1614},1615pushAsync (data, callback) {1616if (Array.isArray(data)) {1617if (_maybeDrain(data)) return1618return data.map(datum => _insert(datum, false, true, callback))1619}1620return _insert(data, false, true, callback);1621},1622kill () {1623off();1624q._tasks.empty();1625},1626unshift (data, callback) {1627if (Array.isArray(data)) {1628if (_maybeDrain(data)) return1629return data.map(datum => _insert(datum, true, false, callback))1630}1631return _insert(data, true, false, callback);1632},1633unshiftAsync (data, callback) {1634if (Array.isArray(data)) {1635if (_maybeDrain(data)) return1636return data.map(datum => _insert(datum, true, true, callback))1637}1638return _insert(data, true, true, callback);1639},1640remove (testFn) {1641q._tasks.remove(testFn);1642},1643process () {1644// Avoid trying to start too many processing operations. This can occur1645// when callbacks resolve synchronously (#1267).1646if (isProcessing) {1647return;1648}1649isProcessing = true;1650while(!q.paused && numRunning < q.concurrency && q._tasks.length){1651var tasks = [], data = [];1652var l = q._tasks.length;1653if (q.payload) l = Math.min(l, q.payload);1654for (var i = 0; i < l; i++) {1655var node = q._tasks.shift();1656tasks.push(node);1657workersList.push(node);1658data.push(node.data);1659}16601661numRunning += 1;16621663if (q._tasks.length === 0) {1664trigger('empty');1665}16661667if (numRunning === q.concurrency) {1668trigger('saturated');1669}16701671var cb = onlyOnce(_createCB(tasks));1672_worker(data, cb);1673}1674isProcessing = false;1675},1676length () {1677return q._tasks.length;1678},1679running () {1680return numRunning;1681},1682workersList () {1683return workersList;1684},1685idle() {1686return q._tasks.length + numRunning === 0;1687},1688pause () {1689q.paused = true;1690},1691resume () {1692if (q.paused === false) { return; }1693q.paused = false;1694setImmediate$1(q.process);1695}1696};1697// define these as fixed properties, so people get useful errors when updating1698Object.defineProperties(q, {1699saturated: {1700writable: false,1701value: eventMethod('saturated')1702},1703unsaturated: {1704writable: false,1705value: eventMethod('unsaturated')1706},1707empty: {1708writable: false,1709value: eventMethod('empty')1710},1711drain: {1712writable: false,1713value: eventMethod('drain')1714},1715error: {1716writable: false,1717value: eventMethod('error')1718},1719});1720return q;1721}17221723/**1724* Creates a `cargo` object with the specified payload. Tasks added to the1725* cargo will be processed altogether (up to the `payload` limit). If the1726* `worker` is in progress, the task is queued until it becomes available. Once1727* the `worker` has completed some tasks, each callback of those tasks is1728* called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)1729* for how `cargo` and `queue` work.1730*1731* While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers1732* at a time, cargo passes an array of tasks to a single worker, repeating1733* when the worker is finished.1734*1735* @name cargo1736* @static1737* @memberOf module:ControlFlow1738* @method1739* @see [async.queue]{@link module:ControlFlow.queue}1740* @category Control Flow1741* @param {AsyncFunction} worker - An asynchronous function for processing an array1742* of queued tasks. Invoked with `(tasks, callback)`.1743* @param {number} [payload=Infinity] - An optional `integer` for determining1744* how many tasks should be processed per round; if omitted, the default is1745* unlimited.1746* @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can1747* attached as certain properties to listen for specific events during the1748* lifecycle of the cargo and inner queue.1749* @example1750*1751* // create a cargo object with payload 21752* var cargo = async.cargo(function(tasks, callback) {1753* for (var i=0; i<tasks.length; i++) {1754* console.log('hello ' + tasks[i].name);1755* }1756* callback();1757* }, 2);1758*1759* // add some items1760* cargo.push({name: 'foo'}, function(err) {1761* console.log('finished processing foo');1762* });1763* cargo.push({name: 'bar'}, function(err) {1764* console.log('finished processing bar');1765* });1766* await cargo.push({name: 'baz'});1767* console.log('finished processing baz');1768*/1769function cargo(worker, payload) {1770return queue(worker, 1, payload);1771}17721773/**1774* Creates a `cargoQueue` object with the specified payload. Tasks added to the1775* cargoQueue will be processed together (up to the `payload` limit) in `concurrency` parallel workers.1776* If the all `workers` are in progress, the task is queued until one becomes available. Once1777* a `worker` has completed some tasks, each callback of those tasks is1778* called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)1779* for how `cargo` and `queue` work.1780*1781* While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers1782* at a time, and [`cargo`]{@link module:ControlFlow.cargo} passes an array of tasks to a single worker,1783* the cargoQueue passes an array of tasks to multiple parallel workers.1784*1785* @name cargoQueue1786* @static1787* @memberOf module:ControlFlow1788* @method1789* @see [async.queue]{@link module:ControlFlow.queue}1790* @see [async.cargo]{@link module:ControlFLow.cargo}1791* @category Control Flow1792* @param {AsyncFunction} worker - An asynchronous function for processing an array1793* of queued tasks. Invoked with `(tasks, callback)`.1794* @param {number} [concurrency=1] - An `integer` for determining how many1795* `worker` functions should be run in parallel. If omitted, the concurrency1796* defaults to `1`. If the concurrency is `0`, an error is thrown.1797* @param {number} [payload=Infinity] - An optional `integer` for determining1798* how many tasks should be processed per round; if omitted, the default is1799* unlimited.1800* @returns {module:ControlFlow.QueueObject} A cargoQueue object to manage the tasks. Callbacks can1801* attached as certain properties to listen for specific events during the1802* lifecycle of the cargoQueue and inner queue.1803* @example1804*1805* // create a cargoQueue object with payload 2 and concurrency 21806* var cargoQueue = async.cargoQueue(function(tasks, callback) {1807* for (var i=0; i<tasks.length; i++) {1808* console.log('hello ' + tasks[i].name);1809* }1810* callback();1811* }, 2, 2);1812*1813* // add some items1814* cargoQueue.push({name: 'foo'}, function(err) {1815* console.log('finished processing foo');1816* });1817* cargoQueue.push({name: 'bar'}, function(err) {1818* console.log('finished processing bar');1819* });1820* cargoQueue.push({name: 'baz'}, function(err) {1821* console.log('finished processing baz');1822* });1823* cargoQueue.push({name: 'boo'}, function(err) {1824* console.log('finished processing boo');1825* });1826*/1827function cargo$1(worker, concurrency, payload) {1828return queue(worker, concurrency, payload);1829}18301831/**1832* Reduces `coll` into a single value using an async `iteratee` to return each1833* successive step. `memo` is the initial state of the reduction. This function1834* only operates in series.1835*1836* For performance reasons, it may make sense to split a call to this function1837* into a parallel map, and then use the normal `Array.prototype.reduce` on the1838* results. This function is for situations where each step in the reduction1839* needs to be async; if you can get the data before reducing it, then it's1840* probably a good idea to do so.1841*1842* @name reduce1843* @static1844* @memberOf module:Collections1845* @method1846* @alias inject1847* @alias foldl1848* @category Collection1849* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.1850* @param {*} memo - The initial state of the reduction.1851* @param {AsyncFunction} iteratee - A function applied to each item in the1852* array to produce the next step in the reduction.1853* The `iteratee` should complete with the next state of the reduction.1854* If the iteratee completes with an error, the reduction is stopped and the1855* main `callback` is immediately called with the error.1856* Invoked with (memo, item, callback).1857* @param {Function} [callback] - A callback which is called after all the1858* `iteratee` functions have finished. Result is the reduced value. Invoked with1859* (err, result).1860* @returns {Promise} a promise, if no callback is passed1861* @example1862*1863* // file1.txt is a file that is 1000 bytes in size1864* // file2.txt is a file that is 2000 bytes in size1865* // file3.txt is a file that is 3000 bytes in size1866* // file4.txt does not exist1867*1868* const fileList = ['file1.txt','file2.txt','file3.txt'];1869* const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt'];1870*1871* // asynchronous function that computes the file size in bytes1872* // file size is added to the memoized value, then returned1873* function getFileSizeInBytes(memo, file, callback) {1874* fs.stat(file, function(err, stat) {1875* if (err) {1876* return callback(err);1877* }1878* callback(null, memo + stat.size);1879* });1880* }1881*1882* // Using callbacks1883* async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) {1884* if (err) {1885* console.log(err);1886* } else {1887* console.log(result);1888* // 60001889* // which is the sum of the file sizes of the three files1890* }1891* });1892*1893* // Error Handling1894* async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) {1895* if (err) {1896* console.log(err);1897* // [ Error: ENOENT: no such file or directory ]1898* } else {1899* console.log(result);1900* }1901* });1902*1903* // Using Promises1904* async.reduce(fileList, 0, getFileSizeInBytes)1905* .then( result => {1906* console.log(result);1907* // 60001908* // which is the sum of the file sizes of the three files1909* }).catch( err => {1910* console.log(err);1911* });1912*1913* // Error Handling1914* async.reduce(withMissingFileList, 0, getFileSizeInBytes)1915* .then( result => {1916* console.log(result);1917* }).catch( err => {1918* console.log(err);1919* // [ Error: ENOENT: no such file or directory ]1920* });1921*1922* // Using async/await1923* async () => {1924* try {1925* let result = await async.reduce(fileList, 0, getFileSizeInBytes);1926* console.log(result);1927* // 60001928* // which is the sum of the file sizes of the three files1929* }1930* catch (err) {1931* console.log(err);1932* }1933* }1934*1935* // Error Handling1936* async () => {1937* try {1938* let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes);1939* console.log(result);1940* }1941* catch (err) {1942* console.log(err);1943* // [ Error: ENOENT: no such file or directory ]1944* }1945* }1946*1947*/1948function reduce(coll, memo, iteratee, callback) {1949callback = once(callback);1950var _iteratee = wrapAsync(iteratee);1951return eachOfSeries$1(coll, (x, i, iterCb) => {1952_iteratee(memo, x, (err, v) => {1953memo = v;1954iterCb(err);1955});1956}, err => callback(err, memo));1957}1958var reduce$1 = awaitify(reduce, 4);19591960/**1961* Version of the compose function that is more natural to read. Each function1962* consumes the return value of the previous function. It is the equivalent of1963* [compose]{@link module:ControlFlow.compose} with the arguments reversed.1964*1965* Each function is executed with the `this` binding of the composed function.1966*1967* @name seq1968* @static1969* @memberOf module:ControlFlow1970* @method1971* @see [async.compose]{@link module:ControlFlow.compose}1972* @category Control Flow1973* @param {...AsyncFunction} functions - the asynchronous functions to compose1974* @returns {Function} a function that composes the `functions` in order1975* @example1976*1977* // Requires lodash (or underscore), express3 and dresende's orm2.1978* // Part of an app, that fetches cats of the logged user.1979* // This example uses `seq` function to avoid overnesting and error1980* // handling clutter.1981* app.get('/cats', function(request, response) {1982* var User = request.models.User;1983* async.seq(1984* User.get.bind(User), // 'User.get' has signature (id, callback(err, data))1985* function(user, fn) {1986* user.getCats(fn); // 'getCats' has signature (callback(err, data))1987* }1988* )(req.session.user_id, function (err, cats) {1989* if (err) {1990* console.error(err);1991* response.json({ status: 'error', message: err.message });1992* } else {1993* response.json({ status: 'ok', message: 'Cats found', data: cats });1994* }1995* });1996* });1997*/1998function seq(...functions) {1999var _functions = functions.map(wrapAsync);2000return function (...args) {2001var that = this;20022003var cb = args[args.length - 1];2004if (typeof cb == 'function') {2005args.pop();2006} else {2007cb = promiseCallback();2008}20092010reduce$1(_functions, args, (newargs, fn, iterCb) => {2011fn.apply(that, newargs.concat((err, ...nextargs) => {2012iterCb(err, nextargs);2013}));2014},2015(err, results) => cb(err, ...results));20162017return cb[PROMISE_SYMBOL]2018};2019}20202021/**2022* Creates a function which is a composition of the passed asynchronous2023* functions. Each function consumes the return value of the function that2024* follows. Composing functions `f()`, `g()`, and `h()` would produce the result2025* of `f(g(h()))`, only this version uses callbacks to obtain the return values.2026*2027* If the last argument to the composed function is not a function, a promise2028* is returned when you call it.2029*2030* Each function is executed with the `this` binding of the composed function.2031*2032* @name compose2033* @static2034* @memberOf module:ControlFlow2035* @method2036* @category Control Flow2037* @param {...AsyncFunction} functions - the asynchronous functions to compose2038* @returns {Function} an asynchronous function that is the composed2039* asynchronous `functions`2040* @example2041*2042* function add1(n, callback) {2043* setTimeout(function () {2044* callback(null, n + 1);2045* }, 10);2046* }2047*2048* function mul3(n, callback) {2049* setTimeout(function () {2050* callback(null, n * 3);2051* }, 10);2052* }2053*2054* var add1mul3 = async.compose(mul3, add1);2055* add1mul3(4, function (err, result) {2056* // result now equals 152057* });2058*/2059function compose(...args) {2060return seq(...args.reverse());2061}20622063/**2064* The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.2065*2066* @name mapLimit2067* @static2068* @memberOf module:Collections2069* @method2070* @see [async.map]{@link module:Collections.map}2071* @category Collection2072* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2073* @param {number} limit - The maximum number of async operations at a time.2074* @param {AsyncFunction} iteratee - An async function to apply to each item in2075* `coll`.2076* The iteratee should complete with the transformed item.2077* Invoked with (item, callback).2078* @param {Function} [callback] - A callback which is called when all `iteratee`2079* functions have finished, or an error occurs. Results is an array of the2080* transformed items from the `coll`. Invoked with (err, results).2081* @returns {Promise} a promise, if no callback is passed2082*/2083function mapLimit (coll, limit, iteratee, callback) {2084return _asyncMap(eachOfLimit(limit), coll, iteratee, callback)2085}2086var mapLimit$1 = awaitify(mapLimit, 4);20872088/**2089* The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.2090*2091* @name concatLimit2092* @static2093* @memberOf module:Collections2094* @method2095* @see [async.concat]{@link module:Collections.concat}2096* @category Collection2097* @alias flatMapLimit2098* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2099* @param {number} limit - The maximum number of async operations at a time.2100* @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,2101* which should use an array as its result. Invoked with (item, callback).2102* @param {Function} [callback] - A callback which is called after all the2103* `iteratee` functions have finished, or an error occurs. Results is an array2104* containing the concatenated results of the `iteratee` function. Invoked with2105* (err, results).2106* @returns A Promise, if no callback is passed2107*/2108function concatLimit(coll, limit, iteratee, callback) {2109var _iteratee = wrapAsync(iteratee);2110return mapLimit$1(coll, limit, (val, iterCb) => {2111_iteratee(val, (err, ...args) => {2112if (err) return iterCb(err);2113return iterCb(err, args);2114});2115}, (err, mapResults) => {2116var result = [];2117for (var i = 0; i < mapResults.length; i++) {2118if (mapResults[i]) {2119result = result.concat(...mapResults[i]);2120}2121}21222123return callback(err, result);2124});2125}2126var concatLimit$1 = awaitify(concatLimit, 4);21272128/**2129* Applies `iteratee` to each item in `coll`, concatenating the results. Returns2130* the concatenated list. The `iteratee`s are called in parallel, and the2131* results are concatenated as they return. The results array will be returned in2132* the original order of `coll` passed to the `iteratee` function.2133*2134* @name concat2135* @static2136* @memberOf module:Collections2137* @method2138* @category Collection2139* @alias flatMap2140* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2141* @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,2142* which should use an array as its result. Invoked with (item, callback).2143* @param {Function} [callback] - A callback which is called after all the2144* `iteratee` functions have finished, or an error occurs. Results is an array2145* containing the concatenated results of the `iteratee` function. Invoked with2146* (err, results).2147* @returns A Promise, if no callback is passed2148* @example2149*2150* // dir1 is a directory that contains file1.txt, file2.txt2151* // dir2 is a directory that contains file3.txt, file4.txt2152* // dir3 is a directory that contains file5.txt2153* // dir4 does not exist2154*2155* let directoryList = ['dir1','dir2','dir3'];2156* let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4'];2157*2158* // Using callbacks2159* async.concat(directoryList, fs.readdir, function(err, results) {2160* if (err) {2161* console.log(err);2162* } else {2163* console.log(results);2164* // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]2165* }2166* });2167*2168* // Error Handling2169* async.concat(withMissingDirectoryList, fs.readdir, function(err, results) {2170* if (err) {2171* console.log(err);2172* // [ Error: ENOENT: no such file or directory ]2173* // since dir4 does not exist2174* } else {2175* console.log(results);2176* }2177* });2178*2179* // Using Promises2180* async.concat(directoryList, fs.readdir)2181* .then(results => {2182* console.log(results);2183* // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]2184* }).catch(err => {2185* console.log(err);2186* });2187*2188* // Error Handling2189* async.concat(withMissingDirectoryList, fs.readdir)2190* .then(results => {2191* console.log(results);2192* }).catch(err => {2193* console.log(err);2194* // [ Error: ENOENT: no such file or directory ]2195* // since dir4 does not exist2196* });2197*2198* // Using async/await2199* async () => {2200* try {2201* let results = await async.concat(directoryList, fs.readdir);2202* console.log(results);2203* // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]2204* } catch (err) {2205* console.log(err);2206* }2207* }2208*2209* // Error Handling2210* async () => {2211* try {2212* let results = await async.concat(withMissingDirectoryList, fs.readdir);2213* console.log(results);2214* } catch (err) {2215* console.log(err);2216* // [ Error: ENOENT: no such file or directory ]2217* // since dir4 does not exist2218* }2219* }2220*2221*/2222function concat(coll, iteratee, callback) {2223return concatLimit$1(coll, Infinity, iteratee, callback)2224}2225var concat$1 = awaitify(concat, 3);22262227/**2228* The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.2229*2230* @name concatSeries2231* @static2232* @memberOf module:Collections2233* @method2234* @see [async.concat]{@link module:Collections.concat}2235* @category Collection2236* @alias flatMapSeries2237* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2238* @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.2239* The iteratee should complete with an array an array of results.2240* Invoked with (item, callback).2241* @param {Function} [callback] - A callback which is called after all the2242* `iteratee` functions have finished, or an error occurs. Results is an array2243* containing the concatenated results of the `iteratee` function. Invoked with2244* (err, results).2245* @returns A Promise, if no callback is passed2246*/2247function concatSeries(coll, iteratee, callback) {2248return concatLimit$1(coll, 1, iteratee, callback)2249}2250var concatSeries$1 = awaitify(concatSeries, 3);22512252/**2253* Returns a function that when called, calls-back with the values provided.2254* Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to2255* [`auto`]{@link module:ControlFlow.auto}.2256*2257* @name constant2258* @static2259* @memberOf module:Utils2260* @method2261* @category Util2262* @param {...*} arguments... - Any number of arguments to automatically invoke2263* callback with.2264* @returns {AsyncFunction} Returns a function that when invoked, automatically2265* invokes the callback with the previous given arguments.2266* @example2267*2268* async.waterfall([2269* async.constant(42),2270* function (value, next) {2271* // value === 422272* },2273* //...2274* ], callback);2275*2276* async.waterfall([2277* async.constant(filename, "utf8"),2278* fs.readFile,2279* function (fileData, next) {2280* //...2281* }2282* //...2283* ], callback);2284*2285* async.auto({2286* hostname: async.constant("https://server.net/"),2287* port: findFreePort,2288* launchServer: ["hostname", "port", function (options, cb) {2289* startServer(options, cb);2290* }],2291* //...2292* }, callback);2293*/2294function constant(...args) {2295return function (...ignoredArgs/*, callback*/) {2296var callback = ignoredArgs.pop();2297return callback(null, ...args);2298};2299}23002301function _createTester(check, getResult) {2302return (eachfn, arr, _iteratee, cb) => {2303var testPassed = false;2304var testResult;2305const iteratee = wrapAsync(_iteratee);2306eachfn(arr, (value, _, callback) => {2307iteratee(value, (err, result) => {2308if (err || err === false) return callback(err);23092310if (check(result) && !testResult) {2311testPassed = true;2312testResult = getResult(true, value);2313return callback(null, breakLoop);2314}2315callback();2316});2317}, err => {2318if (err) return cb(err);2319cb(null, testPassed ? testResult : getResult(false));2320});2321};2322}23232324/**2325* Returns the first value in `coll` that passes an async truth test. The2326* `iteratee` is applied in parallel, meaning the first iteratee to return2327* `true` will fire the detect `callback` with that result. That means the2328* result might not be the first item in the original `coll` (in terms of order)2329* that passes the test.23302331* If order within the original `coll` is important, then look at2332* [`detectSeries`]{@link module:Collections.detectSeries}.2333*2334* @name detect2335* @static2336* @memberOf module:Collections2337* @method2338* @alias find2339* @category Collections2340* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2341* @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.2342* The iteratee must complete with a boolean value as its result.2343* Invoked with (item, callback).2344* @param {Function} [callback] - A callback which is called as soon as any2345* iteratee returns `true`, or after all the `iteratee` functions have finished.2346* Result will be the first item in the array that passes the truth test2347* (iteratee) or the value `undefined` if none passed. Invoked with2348* (err, result).2349* @returns {Promise} a promise, if a callback is omitted2350* @example2351*2352* // dir1 is a directory that contains file1.txt, file2.txt2353* // dir2 is a directory that contains file3.txt, file4.txt2354* // dir3 is a directory that contains file5.txt2355*2356* // asynchronous function that checks if a file exists2357* function fileExists(file, callback) {2358* fs.access(file, fs.constants.F_OK, (err) => {2359* callback(null, !err);2360* });2361* }2362*2363* async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists,2364* function(err, result) {2365* console.log(result);2366* // dir1/file1.txt2367* // result now equals the first file in the list that exists2368* }2369*);2370*2371* // Using Promises2372* async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists)2373* .then(result => {2374* console.log(result);2375* // dir1/file1.txt2376* // result now equals the first file in the list that exists2377* }).catch(err => {2378* console.log(err);2379* });2380*2381* // Using async/await2382* async () => {2383* try {2384* let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists);2385* console.log(result);2386* // dir1/file1.txt2387* // result now equals the file in the list that exists2388* }2389* catch (err) {2390* console.log(err);2391* }2392* }2393*2394*/2395function detect(coll, iteratee, callback) {2396return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback)2397}2398var detect$1 = awaitify(detect, 3);23992400/**2401* The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a2402* time.2403*2404* @name detectLimit2405* @static2406* @memberOf module:Collections2407* @method2408* @see [async.detect]{@link module:Collections.detect}2409* @alias findLimit2410* @category Collections2411* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2412* @param {number} limit - The maximum number of async operations at a time.2413* @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.2414* The iteratee must complete with a boolean value as its result.2415* Invoked with (item, callback).2416* @param {Function} [callback] - A callback which is called as soon as any2417* iteratee returns `true`, or after all the `iteratee` functions have finished.2418* Result will be the first item in the array that passes the truth test2419* (iteratee) or the value `undefined` if none passed. Invoked with2420* (err, result).2421* @returns {Promise} a promise, if a callback is omitted2422*/2423function detectLimit(coll, limit, iteratee, callback) {2424return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback)2425}2426var detectLimit$1 = awaitify(detectLimit, 4);24272428/**2429* The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.2430*2431* @name detectSeries2432* @static2433* @memberOf module:Collections2434* @method2435* @see [async.detect]{@link module:Collections.detect}2436* @alias findSeries2437* @category Collections2438* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2439* @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.2440* The iteratee must complete with a boolean value as its result.2441* Invoked with (item, callback).2442* @param {Function} [callback] - A callback which is called as soon as any2443* iteratee returns `true`, or after all the `iteratee` functions have finished.2444* Result will be the first item in the array that passes the truth test2445* (iteratee) or the value `undefined` if none passed. Invoked with2446* (err, result).2447* @returns {Promise} a promise, if a callback is omitted2448*/2449function detectSeries(coll, iteratee, callback) {2450return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback)2451}24522453var detectSeries$1 = awaitify(detectSeries, 3);24542455function consoleFunc(name) {2456return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => {2457/* istanbul ignore else */2458if (typeof console === 'object') {2459/* istanbul ignore else */2460if (err) {2461/* istanbul ignore else */2462if (console.error) {2463console.error(err);2464}2465} else if (console[name]) { /* istanbul ignore else */2466resultArgs.forEach(x => console[name](x));2467}2468}2469})2470}24712472/**2473* Logs the result of an [`async` function]{@link AsyncFunction} to the2474* `console` using `console.dir` to display the properties of the resulting object.2475* Only works in Node.js or in browsers that support `console.dir` and2476* `console.error` (such as FF and Chrome).2477* If multiple arguments are returned from the async function,2478* `console.dir` is called on each argument in order.2479*2480* @name dir2481* @static2482* @memberOf module:Utils2483* @method2484* @category Util2485* @param {AsyncFunction} function - The function you want to eventually apply2486* all arguments to.2487* @param {...*} arguments... - Any number of arguments to apply to the function.2488* @example2489*2490* // in a module2491* var hello = function(name, callback) {2492* setTimeout(function() {2493* callback(null, {hello: name});2494* }, 1000);2495* };2496*2497* // in the node repl2498* node> async.dir(hello, 'world');2499* {hello: 'world'}2500*/2501var dir = consoleFunc('dir');25022503/**2504* The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in2505* the order of operations, the arguments `test` and `iteratee` are switched.2506*2507* `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.2508*2509* @name doWhilst2510* @static2511* @memberOf module:ControlFlow2512* @method2513* @see [async.whilst]{@link module:ControlFlow.whilst}2514* @category Control Flow2515* @param {AsyncFunction} iteratee - A function which is called each time `test`2516* passes. Invoked with (callback).2517* @param {AsyncFunction} test - asynchronous truth test to perform after each2518* execution of `iteratee`. Invoked with (...args, callback), where `...args` are the2519* non-error args from the previous callback of `iteratee`.2520* @param {Function} [callback] - A callback which is called after the test2521* function has failed and repeated execution of `iteratee` has stopped.2522* `callback` will be passed an error and any arguments passed to the final2523* `iteratee`'s callback. Invoked with (err, [results]);2524* @returns {Promise} a promise, if no callback is passed2525*/2526function doWhilst(iteratee, test, callback) {2527callback = onlyOnce(callback);2528var _fn = wrapAsync(iteratee);2529var _test = wrapAsync(test);2530var results;25312532function next(err, ...args) {2533if (err) return callback(err);2534if (err === false) return;2535results = args;2536_test(...args, check);2537}25382539function check(err, truth) {2540if (err) return callback(err);2541if (err === false) return;2542if (!truth) return callback(null, ...results);2543_fn(next);2544}25452546return check(null, true);2547}25482549var doWhilst$1 = awaitify(doWhilst, 3);25502551/**2552* Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the2553* argument ordering differs from `until`.2554*2555* @name doUntil2556* @static2557* @memberOf module:ControlFlow2558* @method2559* @see [async.doWhilst]{@link module:ControlFlow.doWhilst}2560* @category Control Flow2561* @param {AsyncFunction} iteratee - An async function which is called each time2562* `test` fails. Invoked with (callback).2563* @param {AsyncFunction} test - asynchronous truth test to perform after each2564* execution of `iteratee`. Invoked with (...args, callback), where `...args` are the2565* non-error args from the previous callback of `iteratee`2566* @param {Function} [callback] - A callback which is called after the test2567* function has passed and repeated execution of `iteratee` has stopped. `callback`2568* will be passed an error and any arguments passed to the final `iteratee`'s2569* callback. Invoked with (err, [results]);2570* @returns {Promise} a promise, if no callback is passed2571*/2572function doUntil(iteratee, test, callback) {2573const _test = wrapAsync(test);2574return doWhilst$1(iteratee, (...args) => {2575const cb = args.pop();2576_test(...args, (err, truth) => cb (err, !truth));2577}, callback);2578}25792580function _withoutIndex(iteratee) {2581return (value, index, callback) => iteratee(value, callback);2582}25832584/**2585* Applies the function `iteratee` to each item in `coll`, in parallel.2586* The `iteratee` is called with an item from the list, and a callback for when2587* it has finished. If the `iteratee` passes an error to its `callback`, the2588* main `callback` (for the `each` function) is immediately called with the2589* error.2590*2591* Note, that since this function applies `iteratee` to each item in parallel,2592* there is no guarantee that the iteratee functions will complete in order.2593*2594* @name each2595* @static2596* @memberOf module:Collections2597* @method2598* @alias forEach2599* @category Collection2600* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2601* @param {AsyncFunction} iteratee - An async function to apply to2602* each item in `coll`. Invoked with (item, callback).2603* The array index is not passed to the iteratee.2604* If you need the index, use `eachOf`.2605* @param {Function} [callback] - A callback which is called when all2606* `iteratee` functions have finished, or an error occurs. Invoked with (err).2607* @returns {Promise} a promise, if a callback is omitted2608* @example2609*2610* // dir1 is a directory that contains file1.txt, file2.txt2611* // dir2 is a directory that contains file3.txt, file4.txt2612* // dir3 is a directory that contains file5.txt2613* // dir4 does not exist2614*2615* const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];2616* const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];2617*2618* // asynchronous function that deletes a file2619* const deleteFile = function(file, callback) {2620* fs.unlink(file, callback);2621* };2622*2623* // Using callbacks2624* async.each(fileList, deleteFile, function(err) {2625* if( err ) {2626* console.log(err);2627* } else {2628* console.log('All files have been deleted successfully');2629* }2630* });2631*2632* // Error Handling2633* async.each(withMissingFileList, deleteFile, function(err){2634* console.log(err);2635* // [ Error: ENOENT: no such file or directory ]2636* // since dir4/file2.txt does not exist2637* // dir1/file1.txt could have been deleted2638* });2639*2640* // Using Promises2641* async.each(fileList, deleteFile)2642* .then( () => {2643* console.log('All files have been deleted successfully');2644* }).catch( err => {2645* console.log(err);2646* });2647*2648* // Error Handling2649* async.each(fileList, deleteFile)2650* .then( () => {2651* console.log('All files have been deleted successfully');2652* }).catch( err => {2653* console.log(err);2654* // [ Error: ENOENT: no such file or directory ]2655* // since dir4/file2.txt does not exist2656* // dir1/file1.txt could have been deleted2657* });2658*2659* // Using async/await2660* async () => {2661* try {2662* await async.each(files, deleteFile);2663* }2664* catch (err) {2665* console.log(err);2666* }2667* }2668*2669* // Error Handling2670* async () => {2671* try {2672* await async.each(withMissingFileList, deleteFile);2673* }2674* catch (err) {2675* console.log(err);2676* // [ Error: ENOENT: no such file or directory ]2677* // since dir4/file2.txt does not exist2678* // dir1/file1.txt could have been deleted2679* }2680* }2681*2682*/2683function eachLimit(coll, iteratee, callback) {2684return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback);2685}26862687var each = awaitify(eachLimit, 3);26882689/**2690* The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.2691*2692* @name eachLimit2693* @static2694* @memberOf module:Collections2695* @method2696* @see [async.each]{@link module:Collections.each}2697* @alias forEachLimit2698* @category Collection2699* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2700* @param {number} limit - The maximum number of async operations at a time.2701* @param {AsyncFunction} iteratee - An async function to apply to each item in2702* `coll`.2703* The array index is not passed to the iteratee.2704* If you need the index, use `eachOfLimit`.2705* Invoked with (item, callback).2706* @param {Function} [callback] - A callback which is called when all2707* `iteratee` functions have finished, or an error occurs. Invoked with (err).2708* @returns {Promise} a promise, if a callback is omitted2709*/2710function eachLimit$1(coll, limit, iteratee, callback) {2711return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);2712}2713var eachLimit$2 = awaitify(eachLimit$1, 4);27142715/**2716* The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.2717*2718* Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item2719* in series and therefore the iteratee functions will complete in order.27202721* @name eachSeries2722* @static2723* @memberOf module:Collections2724* @method2725* @see [async.each]{@link module:Collections.each}2726* @alias forEachSeries2727* @category Collection2728* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2729* @param {AsyncFunction} iteratee - An async function to apply to each2730* item in `coll`.2731* The array index is not passed to the iteratee.2732* If you need the index, use `eachOfSeries`.2733* Invoked with (item, callback).2734* @param {Function} [callback] - A callback which is called when all2735* `iteratee` functions have finished, or an error occurs. Invoked with (err).2736* @returns {Promise} a promise, if a callback is omitted2737*/2738function eachSeries(coll, iteratee, callback) {2739return eachLimit$2(coll, 1, iteratee, callback)2740}2741var eachSeries$1 = awaitify(eachSeries, 3);27422743/**2744* Wrap an async function and ensure it calls its callback on a later tick of2745* the event loop. If the function already calls its callback on a next tick,2746* no extra deferral is added. This is useful for preventing stack overflows2747* (`RangeError: Maximum call stack size exceeded`) and generally keeping2748* [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)2749* contained. ES2017 `async` functions are returned as-is -- they are immune2750* to Zalgo's corrupting influences, as they always resolve on a later tick.2751*2752* @name ensureAsync2753* @static2754* @memberOf module:Utils2755* @method2756* @category Util2757* @param {AsyncFunction} fn - an async function, one that expects a node-style2758* callback as its last argument.2759* @returns {AsyncFunction} Returns a wrapped function with the exact same call2760* signature as the function passed in.2761* @example2762*2763* function sometimesAsync(arg, callback) {2764* if (cache[arg]) {2765* return callback(null, cache[arg]); // this would be synchronous!!2766* } else {2767* doSomeIO(arg, callback); // this IO would be asynchronous2768* }2769* }2770*2771* // this has a risk of stack overflows if many results are cached in a row2772* async.mapSeries(args, sometimesAsync, done);2773*2774* // this will defer sometimesAsync's callback if necessary,2775* // preventing stack overflows2776* async.mapSeries(args, async.ensureAsync(sometimesAsync), done);2777*/2778function ensureAsync(fn) {2779if (isAsync(fn)) return fn;2780return function (...args/*, callback*/) {2781var callback = args.pop();2782var sync = true;2783args.push((...innerArgs) => {2784if (sync) {2785setImmediate$1(() => callback(...innerArgs));2786} else {2787callback(...innerArgs);2788}2789});2790fn.apply(this, args);2791sync = false;2792};2793}27942795/**2796* Returns `true` if every element in `coll` satisfies an async test. If any2797* iteratee call returns `false`, the main `callback` is immediately called.2798*2799* @name every2800* @static2801* @memberOf module:Collections2802* @method2803* @alias all2804* @category Collection2805* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2806* @param {AsyncFunction} iteratee - An async truth test to apply to each item2807* in the collection in parallel.2808* The iteratee must complete with a boolean result value.2809* Invoked with (item, callback).2810* @param {Function} [callback] - A callback which is called after all the2811* `iteratee` functions have finished. Result will be either `true` or `false`2812* depending on the values of the async tests. Invoked with (err, result).2813* @returns {Promise} a promise, if no callback provided2814* @example2815*2816* // dir1 is a directory that contains file1.txt, file2.txt2817* // dir2 is a directory that contains file3.txt, file4.txt2818* // dir3 is a directory that contains file5.txt2819* // dir4 does not exist2820*2821* const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt'];2822* const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];2823*2824* // asynchronous function that checks if a file exists2825* function fileExists(file, callback) {2826* fs.access(file, fs.constants.F_OK, (err) => {2827* callback(null, !err);2828* });2829* }2830*2831* // Using callbacks2832* async.every(fileList, fileExists, function(err, result) {2833* console.log(result);2834* // true2835* // result is true since every file exists2836* });2837*2838* async.every(withMissingFileList, fileExists, function(err, result) {2839* console.log(result);2840* // false2841* // result is false since NOT every file exists2842* });2843*2844* // Using Promises2845* async.every(fileList, fileExists)2846* .then( result => {2847* console.log(result);2848* // true2849* // result is true since every file exists2850* }).catch( err => {2851* console.log(err);2852* });2853*2854* async.every(withMissingFileList, fileExists)2855* .then( result => {2856* console.log(result);2857* // false2858* // result is false since NOT every file exists2859* }).catch( err => {2860* console.log(err);2861* });2862*2863* // Using async/await2864* async () => {2865* try {2866* let result = await async.every(fileList, fileExists);2867* console.log(result);2868* // true2869* // result is true since every file exists2870* }2871* catch (err) {2872* console.log(err);2873* }2874* }2875*2876* async () => {2877* try {2878* let result = await async.every(withMissingFileList, fileExists);2879* console.log(result);2880* // false2881* // result is false since NOT every file exists2882* }2883* catch (err) {2884* console.log(err);2885* }2886* }2887*2888*/2889function every(coll, iteratee, callback) {2890return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback)2891}2892var every$1 = awaitify(every, 3);28932894/**2895* The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.2896*2897* @name everyLimit2898* @static2899* @memberOf module:Collections2900* @method2901* @see [async.every]{@link module:Collections.every}2902* @alias allLimit2903* @category Collection2904* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2905* @param {number} limit - The maximum number of async operations at a time.2906* @param {AsyncFunction} iteratee - An async truth test to apply to each item2907* in the collection in parallel.2908* The iteratee must complete with a boolean result value.2909* Invoked with (item, callback).2910* @param {Function} [callback] - A callback which is called after all the2911* `iteratee` functions have finished. Result will be either `true` or `false`2912* depending on the values of the async tests. Invoked with (err, result).2913* @returns {Promise} a promise, if no callback provided2914*/2915function everyLimit(coll, limit, iteratee, callback) {2916return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback)2917}2918var everyLimit$1 = awaitify(everyLimit, 4);29192920/**2921* The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.2922*2923* @name everySeries2924* @static2925* @memberOf module:Collections2926* @method2927* @see [async.every]{@link module:Collections.every}2928* @alias allSeries2929* @category Collection2930* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2931* @param {AsyncFunction} iteratee - An async truth test to apply to each item2932* in the collection in series.2933* The iteratee must complete with a boolean result value.2934* Invoked with (item, callback).2935* @param {Function} [callback] - A callback which is called after all the2936* `iteratee` functions have finished. Result will be either `true` or `false`2937* depending on the values of the async tests. Invoked with (err, result).2938* @returns {Promise} a promise, if no callback provided2939*/2940function everySeries(coll, iteratee, callback) {2941return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback)2942}2943var everySeries$1 = awaitify(everySeries, 3);29442945function filterArray(eachfn, arr, iteratee, callback) {2946var truthValues = new Array(arr.length);2947eachfn(arr, (x, index, iterCb) => {2948iteratee(x, (err, v) => {2949truthValues[index] = !!v;2950iterCb(err);2951});2952}, err => {2953if (err) return callback(err);2954var results = [];2955for (var i = 0; i < arr.length; i++) {2956if (truthValues[i]) results.push(arr[i]);2957}2958callback(null, results);2959});2960}29612962function filterGeneric(eachfn, coll, iteratee, callback) {2963var results = [];2964eachfn(coll, (x, index, iterCb) => {2965iteratee(x, (err, v) => {2966if (err) return iterCb(err);2967if (v) {2968results.push({index, value: x});2969}2970iterCb(err);2971});2972}, err => {2973if (err) return callback(err);2974callback(null, results2975.sort((a, b) => a.index - b.index)2976.map(v => v.value));2977});2978}29792980function _filter(eachfn, coll, iteratee, callback) {2981var filter = isArrayLike(coll) ? filterArray : filterGeneric;2982return filter(eachfn, coll, wrapAsync(iteratee), callback);2983}29842985/**2986* Returns a new array of all the values in `coll` which pass an async truth2987* test. This operation is performed in parallel, but the results array will be2988* in the same order as the original.2989*2990* @name filter2991* @static2992* @memberOf module:Collections2993* @method2994* @alias select2995* @category Collection2996* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2997* @param {Function} iteratee - A truth test to apply to each item in `coll`.2998* The `iteratee` is passed a `callback(err, truthValue)`, which must be called2999* with a boolean argument once it has completed. Invoked with (item, callback).3000* @param {Function} [callback] - A callback which is called after all the3001* `iteratee` functions have finished. Invoked with (err, results).3002* @returns {Promise} a promise, if no callback provided3003* @example3004*3005* // dir1 is a directory that contains file1.txt, file2.txt3006* // dir2 is a directory that contains file3.txt, file4.txt3007* // dir3 is a directory that contains file5.txt3008*3009* const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];3010*3011* // asynchronous function that checks if a file exists3012* function fileExists(file, callback) {3013* fs.access(file, fs.constants.F_OK, (err) => {3014* callback(null, !err);3015* });3016* }3017*3018* // Using callbacks3019* async.filter(files, fileExists, function(err, results) {3020* if(err) {3021* console.log(err);3022* } else {3023* console.log(results);3024* // [ 'dir1/file1.txt', 'dir2/file3.txt' ]3025* // results is now an array of the existing files3026* }3027* });3028*3029* // Using Promises3030* async.filter(files, fileExists)3031* .then(results => {3032* console.log(results);3033* // [ 'dir1/file1.txt', 'dir2/file3.txt' ]3034* // results is now an array of the existing files3035* }).catch(err => {3036* console.log(err);3037* });3038*3039* // Using async/await3040* async () => {3041* try {3042* let results = await async.filter(files, fileExists);3043* console.log(results);3044* // [ 'dir1/file1.txt', 'dir2/file3.txt' ]3045* // results is now an array of the existing files3046* }3047* catch (err) {3048* console.log(err);3049* }3050* }3051*3052*/3053function filter (coll, iteratee, callback) {3054return _filter(eachOf$1, coll, iteratee, callback)3055}3056var filter$1 = awaitify(filter, 3);30573058/**3059* The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a3060* time.3061*3062* @name filterLimit3063* @static3064* @memberOf module:Collections3065* @method3066* @see [async.filter]{@link module:Collections.filter}3067* @alias selectLimit3068* @category Collection3069* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.3070* @param {number} limit - The maximum number of async operations at a time.3071* @param {Function} iteratee - A truth test to apply to each item in `coll`.3072* The `iteratee` is passed a `callback(err, truthValue)`, which must be called3073* with a boolean argument once it has completed. Invoked with (item, callback).3074* @param {Function} [callback] - A callback which is called after all the3075* `iteratee` functions have finished. Invoked with (err, results).3076* @returns {Promise} a promise, if no callback provided3077*/3078function filterLimit (coll, limit, iteratee, callback) {3079return _filter(eachOfLimit(limit), coll, iteratee, callback)3080}3081var filterLimit$1 = awaitify(filterLimit, 4);30823083/**3084* The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.3085*3086* @name filterSeries3087* @static3088* @memberOf module:Collections3089* @method3090* @see [async.filter]{@link module:Collections.filter}3091* @alias selectSeries3092* @category Collection3093* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.3094* @param {Function} iteratee - A truth test to apply to each item in `coll`.3095* The `iteratee` is passed a `callback(err, truthValue)`, which must be called3096* with a boolean argument once it has completed. Invoked with (item, callback).3097* @param {Function} [callback] - A callback which is called after all the3098* `iteratee` functions have finished. Invoked with (err, results)3099* @returns {Promise} a promise, if no callback provided3100*/3101function filterSeries (coll, iteratee, callback) {3102return _filter(eachOfSeries$1, coll, iteratee, callback)3103}3104var filterSeries$1 = awaitify(filterSeries, 3);31053106/**3107* Calls the asynchronous function `fn` with a callback parameter that allows it3108* to call itself again, in series, indefinitely.31093110* If an error is passed to the callback then `errback` is called with the3111* error, and execution stops, otherwise it will never be called.3112*3113* @name forever3114* @static3115* @memberOf module:ControlFlow3116* @method3117* @category Control Flow3118* @param {AsyncFunction} fn - an async function to call repeatedly.3119* Invoked with (next).3120* @param {Function} [errback] - when `fn` passes an error to it's callback,3121* this function will be called, and execution stops. Invoked with (err).3122* @returns {Promise} a promise that rejects if an error occurs and an errback3123* is not passed3124* @example3125*3126* async.forever(3127* function(next) {3128* // next is suitable for passing to things that need a callback(err [, whatever]);3129* // it will result in this function being called again.3130* },3131* function(err) {3132* // if next is called with a value in its first parameter, it will appear3133* // in here as 'err', and execution will stop.3134* }3135* );3136*/3137function forever(fn, errback) {3138var done = onlyOnce(errback);3139var task = wrapAsync(ensureAsync(fn));31403141function next(err) {3142if (err) return done(err);3143if (err === false) return;3144task(next);3145}3146return next();3147}3148var forever$1 = awaitify(forever, 2);31493150/**3151* The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.3152*3153* @name groupByLimit3154* @static3155* @memberOf module:Collections3156* @method3157* @see [async.groupBy]{@link module:Collections.groupBy}3158* @category Collection3159* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.3160* @param {number} limit - The maximum number of async operations at a time.3161* @param {AsyncFunction} iteratee - An async function to apply to each item in3162* `coll`.3163* The iteratee should complete with a `key` to group the value under.3164* Invoked with (value, callback).3165* @param {Function} [callback] - A callback which is called when all `iteratee`3166* functions have finished, or an error occurs. Result is an `Object` whoses3167* properties are arrays of values which returned the corresponding key.3168* @returns {Promise} a promise, if no callback is passed3169*/3170function groupByLimit(coll, limit, iteratee, callback) {3171var _iteratee = wrapAsync(iteratee);3172return mapLimit$1(coll, limit, (val, iterCb) => {3173_iteratee(val, (err, key) => {3174if (err) return iterCb(err);3175return iterCb(err, {key, val});3176});3177}, (err, mapResults) => {3178var result = {};3179// from MDN, handle object having an `hasOwnProperty` prop3180var {hasOwnProperty} = Object.prototype;31813182for (var i = 0; i < mapResults.length; i++) {3183if (mapResults[i]) {3184var {key} = mapResults[i];3185var {val} = mapResults[i];31863187if (hasOwnProperty.call(result, key)) {3188result[key].push(val);3189} else {3190result[key] = [val];3191}3192}3193}31943195return callback(err, result);3196});3197}31983199var groupByLimit$1 = awaitify(groupByLimit, 4);32003201/**3202* Returns a new object, where each value corresponds to an array of items, from3203* `coll`, that returned the corresponding key. That is, the keys of the object3204* correspond to the values passed to the `iteratee` callback.3205*3206* Note: Since this function applies the `iteratee` to each item in parallel,3207* there is no guarantee that the `iteratee` functions will complete in order.3208* However, the values for each key in the `result` will be in the same order as3209* the original `coll`. For Objects, the values will roughly be in the order of3210* the original Objects' keys (but this can vary across JavaScript engines).3211*3212* @name groupBy3213* @static3214* @memberOf module:Collections3215* @method3216* @category Collection3217* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.3218* @param {AsyncFunction} iteratee - An async function to apply to each item in3219* `coll`.3220* The iteratee should complete with a `key` to group the value under.3221* Invoked with (value, callback).3222* @param {Function} [callback] - A callback which is called when all `iteratee`3223* functions have finished, or an error occurs. Result is an `Object` whoses3224* properties are arrays of values which returned the corresponding key.3225* @returns {Promise} a promise, if no callback is passed3226* @example3227*3228* // dir1 is a directory that contains file1.txt, file2.txt3229* // dir2 is a directory that contains file3.txt, file4.txt3230* // dir3 is a directory that contains file5.txt3231* // dir4 does not exist3232*3233* const files = ['dir1/file1.txt','dir2','dir4']3234*3235* // asynchronous function that detects file type as none, file, or directory3236* function detectFile(file, callback) {3237* fs.stat(file, function(err, stat) {3238* if (err) {3239* return callback(null, 'none');3240* }3241* callback(null, stat.isDirectory() ? 'directory' : 'file');3242* });3243* }3244*3245* //Using callbacks3246* async.groupBy(files, detectFile, function(err, result) {3247* if(err) {3248* console.log(err);3249* } else {3250* console.log(result);3251* // {3252* // file: [ 'dir1/file1.txt' ],3253* // none: [ 'dir4' ],3254* // directory: [ 'dir2']3255* // }3256* // result is object containing the files grouped by type3257* }3258* });3259*3260* // Using Promises3261* async.groupBy(files, detectFile)3262* .then( result => {3263* console.log(result);3264* // {3265* // file: [ 'dir1/file1.txt' ],3266* // none: [ 'dir4' ],3267* // directory: [ 'dir2']3268* // }3269* // result is object containing the files grouped by type3270* }).catch( err => {3271* console.log(err);3272* });3273*3274* // Using async/await3275* async () => {3276* try {3277* let result = await async.groupBy(files, detectFile);3278* console.log(result);3279* // {3280* // file: [ 'dir1/file1.txt' ],3281* // none: [ 'dir4' ],3282* // directory: [ 'dir2']3283* // }3284* // result is object containing the files grouped by type3285* }3286* catch (err) {3287* console.log(err);3288* }3289* }3290*3291*/3292function groupBy (coll, iteratee, callback) {3293return groupByLimit$1(coll, Infinity, iteratee, callback)3294}32953296/**3297* The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.3298*3299* @name groupBySeries3300* @static3301* @memberOf module:Collections3302* @method3303* @see [async.groupBy]{@link module:Collections.groupBy}3304* @category Collection3305* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.3306* @param {AsyncFunction} iteratee - An async function to apply to each item in3307* `coll`.3308* The iteratee should complete with a `key` to group the value under.3309* Invoked with (value, callback).3310* @param {Function} [callback] - A callback which is called when all `iteratee`3311* functions have finished, or an error occurs. Result is an `Object` whose3312* properties are arrays of values which returned the corresponding key.3313* @returns {Promise} a promise, if no callback is passed3314*/3315function groupBySeries (coll, iteratee, callback) {3316return groupByLimit$1(coll, 1, iteratee, callback)3317}33183319/**3320* Logs the result of an `async` function to the `console`. Only works in3321* Node.js or in browsers that support `console.log` and `console.error` (such3322* as FF and Chrome). If multiple arguments are returned from the async3323* function, `console.log` is called on each argument in order.3324*3325* @name log3326* @static3327* @memberOf module:Utils3328* @method3329* @category Util3330* @param {AsyncFunction} function - The function you want to eventually apply3331* all arguments to.3332* @param {...*} arguments... - Any number of arguments to apply to the function.3333* @example3334*3335* // in a module3336* var hello = function(name, callback) {3337* setTimeout(function() {3338* callback(null, 'hello ' + name);3339* }, 1000);3340* };3341*3342* // in the node repl3343* node> async.log(hello, 'world');3344* 'hello world'3345*/3346var log = consoleFunc('log');33473348/**3349* The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a3350* time.3351*3352* @name mapValuesLimit3353* @static3354* @memberOf module:Collections3355* @method3356* @see [async.mapValues]{@link module:Collections.mapValues}3357* @category Collection3358* @param {Object} obj - A collection to iterate over.3359* @param {number} limit - The maximum number of async operations at a time.3360* @param {AsyncFunction} iteratee - A function to apply to each value and key3361* in `coll`.3362* The iteratee should complete with the transformed value as its result.3363* Invoked with (value, key, callback).3364* @param {Function} [callback] - A callback which is called when all `iteratee`3365* functions have finished, or an error occurs. `result` is a new object consisting3366* of each key from `obj`, with each transformed value on the right-hand side.3367* Invoked with (err, result).3368* @returns {Promise} a promise, if no callback is passed3369*/3370function mapValuesLimit(obj, limit, iteratee, callback) {3371callback = once(callback);3372var newObj = {};3373var _iteratee = wrapAsync(iteratee);3374return eachOfLimit(limit)(obj, (val, key, next) => {3375_iteratee(val, key, (err, result) => {3376if (err) return next(err);3377newObj[key] = result;3378next(err);3379});3380}, err => callback(err, newObj));3381}33823383var mapValuesLimit$1 = awaitify(mapValuesLimit, 4);33843385/**3386* A relative of [`map`]{@link module:Collections.map}, designed for use with objects.3387*3388* Produces a new Object by mapping each value of `obj` through the `iteratee`3389* function. The `iteratee` is called each `value` and `key` from `obj` and a3390* callback for when it has finished processing. Each of these callbacks takes3391* two arguments: an `error`, and the transformed item from `obj`. If `iteratee`3392* passes an error to its callback, the main `callback` (for the `mapValues`3393* function) is immediately called with the error.3394*3395* Note, the order of the keys in the result is not guaranteed. The keys will3396* be roughly in the order they complete, (but this is very engine-specific)3397*3398* @name mapValues3399* @static3400* @memberOf module:Collections3401* @method3402* @category Collection3403* @param {Object} obj - A collection to iterate over.3404* @param {AsyncFunction} iteratee - A function to apply to each value and key3405* in `coll`.3406* The iteratee should complete with the transformed value as its result.3407* Invoked with (value, key, callback).3408* @param {Function} [callback] - A callback which is called when all `iteratee`3409* functions have finished, or an error occurs. `result` is a new object consisting3410* of each key from `obj`, with each transformed value on the right-hand side.3411* Invoked with (err, result).3412* @returns {Promise} a promise, if no callback is passed3413* @example3414*3415* // file1.txt is a file that is 1000 bytes in size3416* // file2.txt is a file that is 2000 bytes in size3417* // file3.txt is a file that is 3000 bytes in size3418* // file4.txt does not exist3419*3420* const fileMap = {3421* f1: 'file1.txt',3422* f2: 'file2.txt',3423* f3: 'file3.txt'3424* };3425*3426* const withMissingFileMap = {3427* f1: 'file1.txt',3428* f2: 'file2.txt',3429* f3: 'file4.txt'3430* };3431*3432* // asynchronous function that returns the file size in bytes3433* function getFileSizeInBytes(file, key, callback) {3434* fs.stat(file, function(err, stat) {3435* if (err) {3436* return callback(err);3437* }3438* callback(null, stat.size);3439* });3440* }3441*3442* // Using callbacks3443* async.mapValues(fileMap, getFileSizeInBytes, function(err, result) {3444* if (err) {3445* console.log(err);3446* } else {3447* console.log(result);3448* // result is now a map of file size in bytes for each file, e.g.3449* // {3450* // f1: 1000,3451* // f2: 2000,3452* // f3: 30003453* // }3454* }3455* });3456*3457* // Error handling3458* async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) {3459* if (err) {3460* console.log(err);3461* // [ Error: ENOENT: no such file or directory ]3462* } else {3463* console.log(result);3464* }3465* });3466*3467* // Using Promises3468* async.mapValues(fileMap, getFileSizeInBytes)3469* .then( result => {3470* console.log(result);3471* // result is now a map of file size in bytes for each file, e.g.3472* // {3473* // f1: 1000,3474* // f2: 2000,3475* // f3: 30003476* // }3477* }).catch (err => {3478* console.log(err);3479* });3480*3481* // Error Handling3482* async.mapValues(withMissingFileMap, getFileSizeInBytes)3483* .then( result => {3484* console.log(result);3485* }).catch (err => {3486* console.log(err);3487* // [ Error: ENOENT: no such file or directory ]3488* });3489*3490* // Using async/await3491* async () => {3492* try {3493* let result = await async.mapValues(fileMap, getFileSizeInBytes);3494* console.log(result);3495* // result is now a map of file size in bytes for each file, e.g.3496* // {3497* // f1: 1000,3498* // f2: 2000,3499* // f3: 30003500* // }3501* }3502* catch (err) {3503* console.log(err);3504* }3505* }3506*3507* // Error Handling3508* async () => {3509* try {3510* let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes);3511* console.log(result);3512* }3513* catch (err) {3514* console.log(err);3515* // [ Error: ENOENT: no such file or directory ]3516* }3517* }3518*3519*/3520function mapValues(obj, iteratee, callback) {3521return mapValuesLimit$1(obj, Infinity, iteratee, callback)3522}35233524/**3525* The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.3526*3527* @name mapValuesSeries3528* @static3529* @memberOf module:Collections3530* @method3531* @see [async.mapValues]{@link module:Collections.mapValues}3532* @category Collection3533* @param {Object} obj - A collection to iterate over.3534* @param {AsyncFunction} iteratee - A function to apply to each value and key3535* in `coll`.3536* The iteratee should complete with the transformed value as its result.3537* Invoked with (value, key, callback).3538* @param {Function} [callback] - A callback which is called when all `iteratee`3539* functions have finished, or an error occurs. `result` is a new object consisting3540* of each key from `obj`, with each transformed value on the right-hand side.3541* Invoked with (err, result).3542* @returns {Promise} a promise, if no callback is passed3543*/3544function mapValuesSeries(obj, iteratee, callback) {3545return mapValuesLimit$1(obj, 1, iteratee, callback)3546}35473548/**3549* Caches the results of an async function. When creating a hash to store3550* function results against, the callback is omitted from the hash and an3551* optional hash function can be used.3552*3553* **Note: if the async function errs, the result will not be cached and3554* subsequent calls will call the wrapped function.**3555*3556* If no hash function is specified, the first argument is used as a hash key,3557* which may work reasonably if it is a string or a data type that converts to a3558* distinct string. Note that objects and arrays will not behave reasonably.3559* Neither will cases where the other arguments are significant. In such cases,3560* specify your own hash function.3561*3562* The cache of results is exposed as the `memo` property of the function3563* returned by `memoize`.3564*3565* @name memoize3566* @static3567* @memberOf module:Utils3568* @method3569* @category Util3570* @param {AsyncFunction} fn - The async function to proxy and cache results from.3571* @param {Function} hasher - An optional function for generating a custom hash3572* for storing results. It has all the arguments applied to it apart from the3573* callback, and must be synchronous.3574* @returns {AsyncFunction} a memoized version of `fn`3575* @example3576*3577* var slow_fn = function(name, callback) {3578* // do something3579* callback(null, result);3580* };3581* var fn = async.memoize(slow_fn);3582*3583* // fn can now be used as if it were slow_fn3584* fn('some name', function() {3585* // callback3586* });3587*/3588function memoize(fn, hasher = v => v) {3589var memo = Object.create(null);3590var queues = Object.create(null);3591var _fn = wrapAsync(fn);3592var memoized = initialParams((args, callback) => {3593var key = hasher(...args);3594if (key in memo) {3595setImmediate$1(() => callback(null, ...memo[key]));3596} else if (key in queues) {3597queues[key].push(callback);3598} else {3599queues[key] = [callback];3600_fn(...args, (err, ...resultArgs) => {3601// #1465 don't memoize if an error occurred3602if (!err) {3603memo[key] = resultArgs;3604}3605var q = queues[key];3606delete queues[key];3607for (var i = 0, l = q.length; i < l; i++) {3608q[i](err, ...resultArgs);3609}3610});3611}3612});3613memoized.memo = memo;3614memoized.unmemoized = fn;3615return memoized;3616}36173618/* istanbul ignore file */36193620/**3621* Calls `callback` on a later loop around the event loop. In Node.js this just3622* calls `process.nextTick`. In the browser it will use `setImmediate` if3623* available, otherwise `setTimeout(callback, 0)`, which means other higher3624* priority events may precede the execution of `callback`.3625*3626* This is used internally for browser-compatibility purposes.3627*3628* @name nextTick3629* @static3630* @memberOf module:Utils3631* @method3632* @see [async.setImmediate]{@link module:Utils.setImmediate}3633* @category Util3634* @param {Function} callback - The function to call on a later loop around3635* the event loop. Invoked with (args...).3636* @param {...*} args... - any number of additional arguments to pass to the3637* callback on the next tick.3638* @example3639*3640* var call_order = [];3641* async.nextTick(function() {3642* call_order.push('two');3643* // call_order now equals ['one','two']3644* });3645* call_order.push('one');3646*3647* async.setImmediate(function (a, b, c) {3648* // a, b, and c equal 1, 2, and 33649* }, 1, 2, 3);3650*/3651var _defer$1;36523653if (hasNextTick) {3654_defer$1 = process.nextTick;3655} else if (hasSetImmediate) {3656_defer$1 = setImmediate;3657} else {3658_defer$1 = fallback;3659}36603661var nextTick = wrap(_defer$1);36623663var parallel = awaitify((eachfn, tasks, callback) => {3664var results = isArrayLike(tasks) ? [] : {};36653666eachfn(tasks, (task, key, taskCb) => {3667wrapAsync(task)((err, ...result) => {3668if (result.length < 2) {3669[result] = result;3670}3671results[key] = result;3672taskCb(err);3673});3674}, err => callback(err, results));3675}, 3);36763677/**3678* Run the `tasks` collection of functions in parallel, without waiting until3679* the previous function has completed. If any of the functions pass an error to3680* its callback, the main `callback` is immediately called with the value of the3681* error. Once the `tasks` have completed, the results are passed to the final3682* `callback` as an array.3683*3684* **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about3685* parallel execution of code. If your tasks do not use any timers or perform3686* any I/O, they will actually be executed in series. Any synchronous setup3687* sections for each task will happen one after the other. JavaScript remains3688* single-threaded.3689*3690* **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the3691* execution of other tasks when a task fails.3692*3693* It is also possible to use an object instead of an array. Each property will3694* be run as a function and the results will be passed to the final `callback`3695* as an object instead of an array. This can be a more readable way of handling3696* results from {@link async.parallel}.3697*3698* @name parallel3699* @static3700* @memberOf module:ControlFlow3701* @method3702* @category Control Flow3703* @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of3704* [async functions]{@link AsyncFunction} to run.3705* Each async function can complete with any number of optional `result` values.3706* @param {Function} [callback] - An optional callback to run once all the3707* functions have completed successfully. This function gets a results array3708* (or object) containing all the result arguments passed to the task callbacks.3709* Invoked with (err, results).3710* @returns {Promise} a promise, if a callback is not passed3711*3712* @example3713*3714* //Using Callbacks3715* async.parallel([3716* function(callback) {3717* setTimeout(function() {3718* callback(null, 'one');3719* }, 200);3720* },3721* function(callback) {3722* setTimeout(function() {3723* callback(null, 'two');3724* }, 100);3725* }3726* ], function(err, results) {3727* console.log(results);3728* // results is equal to ['one','two'] even though3729* // the second function had a shorter timeout.3730* });3731*3732* // an example using an object instead of an array3733* async.parallel({3734* one: function(callback) {3735* setTimeout(function() {3736* callback(null, 1);3737* }, 200);3738* },3739* two: function(callback) {3740* setTimeout(function() {3741* callback(null, 2);3742* }, 100);3743* }3744* }, function(err, results) {3745* console.log(results);3746* // results is equal to: { one: 1, two: 2 }3747* });3748*3749* //Using Promises3750* async.parallel([3751* function(callback) {3752* setTimeout(function() {3753* callback(null, 'one');3754* }, 200);3755* },3756* function(callback) {3757* setTimeout(function() {3758* callback(null, 'two');3759* }, 100);3760* }3761* ]).then(results => {3762* console.log(results);3763* // results is equal to ['one','two'] even though3764* // the second function had a shorter timeout.3765* }).catch(err => {3766* console.log(err);3767* });3768*3769* // an example using an object instead of an array3770* async.parallel({3771* one: function(callback) {3772* setTimeout(function() {3773* callback(null, 1);3774* }, 200);3775* },3776* two: function(callback) {3777* setTimeout(function() {3778* callback(null, 2);3779* }, 100);3780* }3781* }).then(results => {3782* console.log(results);3783* // results is equal to: { one: 1, two: 2 }3784* }).catch(err => {3785* console.log(err);3786* });3787*3788* //Using async/await3789* async () => {3790* try {3791* let results = await async.parallel([3792* function(callback) {3793* setTimeout(function() {3794* callback(null, 'one');3795* }, 200);3796* },3797* function(callback) {3798* setTimeout(function() {3799* callback(null, 'two');3800* }, 100);3801* }3802* ]);3803* console.log(results);3804* // results is equal to ['one','two'] even though3805* // the second function had a shorter timeout.3806* }3807* catch (err) {3808* console.log(err);3809* }3810* }3811*3812* // an example using an object instead of an array3813* async () => {3814* try {3815* let results = await async.parallel({3816* one: function(callback) {3817* setTimeout(function() {3818* callback(null, 1);3819* }, 200);3820* },3821* two: function(callback) {3822* setTimeout(function() {3823* callback(null, 2);3824* }, 100);3825* }3826* });3827* console.log(results);3828* // results is equal to: { one: 1, two: 2 }3829* }3830* catch (err) {3831* console.log(err);3832* }3833* }3834*3835*/3836function parallel$1(tasks, callback) {3837return parallel(eachOf$1, tasks, callback);3838}38393840/**3841* The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a3842* time.3843*3844* @name parallelLimit3845* @static3846* @memberOf module:ControlFlow3847* @method3848* @see [async.parallel]{@link module:ControlFlow.parallel}3849* @category Control Flow3850* @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of3851* [async functions]{@link AsyncFunction} to run.3852* Each async function can complete with any number of optional `result` values.3853* @param {number} limit - The maximum number of async operations at a time.3854* @param {Function} [callback] - An optional callback to run once all the3855* functions have completed successfully. This function gets a results array3856* (or object) containing all the result arguments passed to the task callbacks.3857* Invoked with (err, results).3858* @returns {Promise} a promise, if a callback is not passed3859*/3860function parallelLimit(tasks, limit, callback) {3861return parallel(eachOfLimit(limit), tasks, callback);3862}38633864/**3865* A queue of tasks for the worker function to complete.3866* @typedef {Iterable} QueueObject3867* @memberOf module:ControlFlow3868* @property {Function} length - a function returning the number of items3869* waiting to be processed. Invoke with `queue.length()`.3870* @property {boolean} started - a boolean indicating whether or not any3871* items have been pushed and processed by the queue.3872* @property {Function} running - a function returning the number of items3873* currently being processed. Invoke with `queue.running()`.3874* @property {Function} workersList - a function returning the array of items3875* currently being processed. Invoke with `queue.workersList()`.3876* @property {Function} idle - a function returning false if there are items3877* waiting or being processed, or true if not. Invoke with `queue.idle()`.3878* @property {number} concurrency - an integer for determining how many `worker`3879* functions should be run in parallel. This property can be changed after a3880* `queue` is created to alter the concurrency on-the-fly.3881* @property {number} payload - an integer that specifies how many items are3882* passed to the worker function at a time. only applies if this is a3883* [cargo]{@link module:ControlFlow.cargo} object3884* @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback`3885* once the `worker` has finished processing the task. Instead of a single task,3886* a `tasks` array can be submitted. The respective callback is used for every3887* task in the list. Invoke with `queue.push(task, [callback])`,3888* @property {AsyncFunction} unshift - add a new task to the front of the `queue`.3889* Invoke with `queue.unshift(task, [callback])`.3890* @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns3891* a promise that rejects if an error occurs.3892* @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns3893* a promise that rejects if an error occurs.3894* @property {Function} remove - remove items from the queue that match a test3895* function. The test function will be passed an object with a `data` property,3896* and a `priority` property, if this is a3897* [priorityQueue]{@link module:ControlFlow.priorityQueue} object.3898* Invoked with `queue.remove(testFn)`, where `testFn` is of the form3899* `function ({data, priority}) {}` and returns a Boolean.3900* @property {Function} saturated - a function that sets a callback that is3901* called when the number of running workers hits the `concurrency` limit, and3902* further tasks will be queued. If the callback is omitted, `q.saturated()`3903* returns a promise for the next occurrence.3904* @property {Function} unsaturated - a function that sets a callback that is3905* called when the number of running workers is less than the `concurrency` &3906* `buffer` limits, and further tasks will not be queued. If the callback is3907* omitted, `q.unsaturated()` returns a promise for the next occurrence.3908* @property {number} buffer - A minimum threshold buffer in order to say that3909* the `queue` is `unsaturated`.3910* @property {Function} empty - a function that sets a callback that is called3911* when the last item from the `queue` is given to a `worker`. If the callback3912* is omitted, `q.empty()` returns a promise for the next occurrence.3913* @property {Function} drain - a function that sets a callback that is called3914* when the last item from the `queue` has returned from the `worker`. If the3915* callback is omitted, `q.drain()` returns a promise for the next occurrence.3916* @property {Function} error - a function that sets a callback that is called3917* when a task errors. Has the signature `function(error, task)`. If the3918* callback is omitted, `error()` returns a promise that rejects on the next3919* error.3920* @property {boolean} paused - a boolean for determining whether the queue is3921* in a paused state.3922* @property {Function} pause - a function that pauses the processing of tasks3923* until `resume()` is called. Invoke with `queue.pause()`.3924* @property {Function} resume - a function that resumes the processing of3925* queued tasks when the queue is paused. Invoke with `queue.resume()`.3926* @property {Function} kill - a function that removes the `drain` callback and3927* empties remaining tasks from the queue forcing it to go idle. No more tasks3928* should be pushed to the queue after calling this function. Invoke with `queue.kill()`.3929*3930* @example3931* const q = async.queue(worker, 2)3932* q.push(item1)3933* q.push(item2)3934* q.push(item3)3935* // queues are iterable, spread into an array to inspect3936* const items = [...q] // [item1, item2, item3]3937* // or use for of3938* for (let item of q) {3939* console.log(item)3940* }3941*3942* q.drain(() => {3943* console.log('all done')3944* })3945* // or3946* await q.drain()3947*/39483949/**3950* Creates a `queue` object with the specified `concurrency`. Tasks added to the3951* `queue` are processed in parallel (up to the `concurrency` limit). If all3952* `worker`s are in progress, the task is queued until one becomes available.3953* Once a `worker` completes a `task`, that `task`'s callback is called.3954*3955* @name queue3956* @static3957* @memberOf module:ControlFlow3958* @method3959* @category Control Flow3960* @param {AsyncFunction} worker - An async function for processing a queued task.3961* If you want to handle errors from an individual task, pass a callback to3962* `q.push()`. Invoked with (task, callback).3963* @param {number} [concurrency=1] - An `integer` for determining how many3964* `worker` functions should be run in parallel. If omitted, the concurrency3965* defaults to `1`. If the concurrency is `0`, an error is thrown.3966* @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be3967* attached as certain properties to listen for specific events during the3968* lifecycle of the queue.3969* @example3970*3971* // create a queue object with concurrency 23972* var q = async.queue(function(task, callback) {3973* console.log('hello ' + task.name);3974* callback();3975* }, 2);3976*3977* // assign a callback3978* q.drain(function() {3979* console.log('all items have been processed');3980* });3981* // or await the end3982* await q.drain()3983*3984* // assign an error callback3985* q.error(function(err, task) {3986* console.error('task experienced an error');3987* });3988*3989* // add some items to the queue3990* q.push({name: 'foo'}, function(err) {3991* console.log('finished processing foo');3992* });3993* // callback is optional3994* q.push({name: 'bar'});3995*3996* // add some items to the queue (batch-wise)3997* q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {3998* console.log('finished processing item');3999* });4000*4001* // add some items to the front of the queue4002* q.unshift({name: 'bar'}, function (err) {4003* console.log('finished processing bar');4004* });4005*/4006function queue$1 (worker, concurrency) {4007var _worker = wrapAsync(worker);4008return queue((items, cb) => {4009_worker(items[0], cb);4010}, concurrency, 1);4011}40124013// Binary min-heap implementation used for priority queue.4014// Implementation is stable, i.e. push time is considered for equal priorities4015class Heap {4016constructor() {4017this.heap = [];4018this.pushCount = Number.MIN_SAFE_INTEGER;4019}40204021get length() {4022return this.heap.length;4023}40244025empty () {4026this.heap = [];4027return this;4028}40294030percUp(index) {4031let p;40324033while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) {4034let t = this.heap[index];4035this.heap[index] = this.heap[p];4036this.heap[p] = t;40374038index = p;4039}4040}40414042percDown(index) {4043let l;40444045while ((l=leftChi(index)) < this.heap.length) {4046if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) {4047l = l+1;4048}40494050if (smaller(this.heap[index], this.heap[l])) {4051break;4052}40534054let t = this.heap[index];4055this.heap[index] = this.heap[l];4056this.heap[l] = t;40574058index = l;4059}4060}40614062push(node) {4063node.pushCount = ++this.pushCount;4064this.heap.push(node);4065this.percUp(this.heap.length-1);4066}40674068unshift(node) {4069return this.heap.push(node);4070}40714072shift() {4073let [top] = this.heap;40744075this.heap[0] = this.heap[this.heap.length-1];4076this.heap.pop();4077this.percDown(0);40784079return top;4080}40814082toArray() {4083return [...this];4084}40854086*[Symbol.iterator] () {4087for (let i = 0; i < this.heap.length; i++) {4088yield this.heap[i].data;4089}4090}40914092remove (testFn) {4093let j = 0;4094for (let i = 0; i < this.heap.length; i++) {4095if (!testFn(this.heap[i])) {4096this.heap[j] = this.heap[i];4097j++;4098}4099}41004101this.heap.splice(j);41024103for (let i = parent(this.heap.length-1); i >= 0; i--) {4104this.percDown(i);4105}41064107return this;4108}4109}41104111function leftChi(i) {4112return (i<<1)+1;4113}41144115function parent(i) {4116return ((i+1)>>1)-1;4117}41184119function smaller(x, y) {4120if (x.priority !== y.priority) {4121return x.priority < y.priority;4122}4123else {4124return x.pushCount < y.pushCount;4125}4126}41274128/**4129* The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and4130* completed in ascending priority order.4131*4132* @name priorityQueue4133* @static4134* @memberOf module:ControlFlow4135* @method4136* @see [async.queue]{@link module:ControlFlow.queue}4137* @category Control Flow4138* @param {AsyncFunction} worker - An async function for processing a queued task.4139* If you want to handle errors from an individual task, pass a callback to4140* `q.push()`.4141* Invoked with (task, callback).4142* @param {number} concurrency - An `integer` for determining how many `worker`4143* functions should be run in parallel. If omitted, the concurrency defaults to4144* `1`. If the concurrency is `0`, an error is thrown.4145* @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three4146* differences between `queue` and `priorityQueue` objects:4147* * `push(task, priority, [callback])` - `priority` should be a number. If an4148* array of `tasks` is given, all tasks will be assigned the same priority.4149* * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`,4150* except this returns a promise that rejects if an error occurs.4151* * The `unshift` and `unshiftAsync` methods were removed.4152*/4153function priorityQueue(worker, concurrency) {4154// Start with a normal queue4155var q = queue$1(worker, concurrency);41564157var {4158push,4159pushAsync4160} = q;41614162q._tasks = new Heap();4163q._createTaskItem = ({data, priority}, callback) => {4164return {4165data,4166priority,4167callback4168};4169};41704171function createDataItems(tasks, priority) {4172if (!Array.isArray(tasks)) {4173return {data: tasks, priority};4174}4175return tasks.map(data => { return {data, priority}; });4176}41774178// Override push to accept second parameter representing priority4179q.push = function(data, priority = 0, callback) {4180return push(createDataItems(data, priority), callback);4181};41824183q.pushAsync = function(data, priority = 0, callback) {4184return pushAsync(createDataItems(data, priority), callback);4185};41864187// Remove unshift functions4188delete q.unshift;4189delete q.unshiftAsync;41904191return q;4192}41934194/**4195* Runs the `tasks` array of functions in parallel, without waiting until the4196* previous function has completed. Once any of the `tasks` complete or pass an4197* error to its callback, the main `callback` is immediately called. It's4198* equivalent to `Promise.race()`.4199*4200* @name race4201* @static4202* @memberOf module:ControlFlow4203* @method4204* @category Control Flow4205* @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}4206* to run. Each function can complete with an optional `result` value.4207* @param {Function} callback - A callback to run once any of the functions have4208* completed. This function gets an error or result from the first function that4209* completed. Invoked with (err, result).4210* @returns {Promise} a promise, if a callback is omitted4211* @example4212*4213* async.race([4214* function(callback) {4215* setTimeout(function() {4216* callback(null, 'one');4217* }, 200);4218* },4219* function(callback) {4220* setTimeout(function() {4221* callback(null, 'two');4222* }, 100);4223* }4224* ],4225* // main callback4226* function(err, result) {4227* // the result will be equal to 'two' as it finishes earlier4228* });4229*/4230function race(tasks, callback) {4231callback = once(callback);4232if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));4233if (!tasks.length) return callback();4234for (var i = 0, l = tasks.length; i < l; i++) {4235wrapAsync(tasks[i])(callback);4236}4237}42384239var race$1 = awaitify(race, 2);42404241/**4242* Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.4243*4244* @name reduceRight4245* @static4246* @memberOf module:Collections4247* @method4248* @see [async.reduce]{@link module:Collections.reduce}4249* @alias foldr4250* @category Collection4251* @param {Array} array - A collection to iterate over.4252* @param {*} memo - The initial state of the reduction.4253* @param {AsyncFunction} iteratee - A function applied to each item in the4254* array to produce the next step in the reduction.4255* The `iteratee` should complete with the next state of the reduction.4256* If the iteratee completes with an error, the reduction is stopped and the4257* main `callback` is immediately called with the error.4258* Invoked with (memo, item, callback).4259* @param {Function} [callback] - A callback which is called after all the4260* `iteratee` functions have finished. Result is the reduced value. Invoked with4261* (err, result).4262* @returns {Promise} a promise, if no callback is passed4263*/4264function reduceRight (array, memo, iteratee, callback) {4265var reversed = [...array].reverse();4266return reduce$1(reversed, memo, iteratee, callback);4267}42684269/**4270* Wraps the async function in another function that always completes with a4271* result object, even when it errors.4272*4273* The result object has either the property `error` or `value`.4274*4275* @name reflect4276* @static4277* @memberOf module:Utils4278* @method4279* @category Util4280* @param {AsyncFunction} fn - The async function you want to wrap4281* @returns {Function} - A function that always passes null to it's callback as4282* the error. The second argument to the callback will be an `object` with4283* either an `error` or a `value` property.4284* @example4285*4286* async.parallel([4287* async.reflect(function(callback) {4288* // do some stuff ...4289* callback(null, 'one');4290* }),4291* async.reflect(function(callback) {4292* // do some more stuff but error ...4293* callback('bad stuff happened');4294* }),4295* async.reflect(function(callback) {4296* // do some more stuff ...4297* callback(null, 'two');4298* })4299* ],4300* // optional callback4301* function(err, results) {4302* // values4303* // results[0].value = 'one'4304* // results[1].error = 'bad stuff happened'4305* // results[2].value = 'two'4306* });4307*/4308function reflect(fn) {4309var _fn = wrapAsync(fn);4310return initialParams(function reflectOn(args, reflectCallback) {4311args.push((error, ...cbArgs) => {4312let retVal = {};4313if (error) {4314retVal.error = error;4315}4316if (cbArgs.length > 0){4317var value = cbArgs;4318if (cbArgs.length <= 1) {4319[value] = cbArgs;4320}4321retVal.value = value;4322}4323reflectCallback(null, retVal);4324});43254326return _fn.apply(this, args);4327});4328}43294330/**4331* A helper function that wraps an array or an object of functions with `reflect`.4332*4333* @name reflectAll4334* @static4335* @memberOf module:Utils4336* @method4337* @see [async.reflect]{@link module:Utils.reflect}4338* @category Util4339* @param {Array|Object|Iterable} tasks - The collection of4340* [async functions]{@link AsyncFunction} to wrap in `async.reflect`.4341* @returns {Array} Returns an array of async functions, each wrapped in4342* `async.reflect`4343* @example4344*4345* let tasks = [4346* function(callback) {4347* setTimeout(function() {4348* callback(null, 'one');4349* }, 200);4350* },4351* function(callback) {4352* // do some more stuff but error ...4353* callback(new Error('bad stuff happened'));4354* },4355* function(callback) {4356* setTimeout(function() {4357* callback(null, 'two');4358* }, 100);4359* }4360* ];4361*4362* async.parallel(async.reflectAll(tasks),4363* // optional callback4364* function(err, results) {4365* // values4366* // results[0].value = 'one'4367* // results[1].error = Error('bad stuff happened')4368* // results[2].value = 'two'4369* });4370*4371* // an example using an object instead of an array4372* let tasks = {4373* one: function(callback) {4374* setTimeout(function() {4375* callback(null, 'one');4376* }, 200);4377* },4378* two: function(callback) {4379* callback('two');4380* },4381* three: function(callback) {4382* setTimeout(function() {4383* callback(null, 'three');4384* }, 100);4385* }4386* };4387*4388* async.parallel(async.reflectAll(tasks),4389* // optional callback4390* function(err, results) {4391* // values4392* // results.one.value = 'one'4393* // results.two.error = 'two'4394* // results.three.value = 'three'4395* });4396*/4397function reflectAll(tasks) {4398var results;4399if (Array.isArray(tasks)) {4400results = tasks.map(reflect);4401} else {4402results = {};4403Object.keys(tasks).forEach(key => {4404results[key] = reflect.call(this, tasks[key]);4405});4406}4407return results;4408}44094410function reject(eachfn, arr, _iteratee, callback) {4411const iteratee = wrapAsync(_iteratee);4412return _filter(eachfn, arr, (value, cb) => {4413iteratee(value, (err, v) => {4414cb(err, !v);4415});4416}, callback);4417}44184419/**4420* The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.4421*4422* @name reject4423* @static4424* @memberOf module:Collections4425* @method4426* @see [async.filter]{@link module:Collections.filter}4427* @category Collection4428* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.4429* @param {Function} iteratee - An async truth test to apply to each item in4430* `coll`.4431* The should complete with a boolean value as its `result`.4432* Invoked with (item, callback).4433* @param {Function} [callback] - A callback which is called after all the4434* `iteratee` functions have finished. Invoked with (err, results).4435* @returns {Promise} a promise, if no callback is passed4436* @example4437*4438* // dir1 is a directory that contains file1.txt, file2.txt4439* // dir2 is a directory that contains file3.txt, file4.txt4440* // dir3 is a directory that contains file5.txt4441*4442* const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];4443*4444* // asynchronous function that checks if a file exists4445* function fileExists(file, callback) {4446* fs.access(file, fs.constants.F_OK, (err) => {4447* callback(null, !err);4448* });4449* }4450*4451* // Using callbacks4452* async.reject(fileList, fileExists, function(err, results) {4453* // [ 'dir3/file6.txt' ]4454* // results now equals an array of the non-existing files4455* });4456*4457* // Using Promises4458* async.reject(fileList, fileExists)4459* .then( results => {4460* console.log(results);4461* // [ 'dir3/file6.txt' ]4462* // results now equals an array of the non-existing files4463* }).catch( err => {4464* console.log(err);4465* });4466*4467* // Using async/await4468* async () => {4469* try {4470* let results = await async.reject(fileList, fileExists);4471* console.log(results);4472* // [ 'dir3/file6.txt' ]4473* // results now equals an array of the non-existing files4474* }4475* catch (err) {4476* console.log(err);4477* }4478* }4479*4480*/4481function reject$1 (coll, iteratee, callback) {4482return reject(eachOf$1, coll, iteratee, callback)4483}4484var reject$2 = awaitify(reject$1, 3);44854486/**4487* The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a4488* time.4489*4490* @name rejectLimit4491* @static4492* @memberOf module:Collections4493* @method4494* @see [async.reject]{@link module:Collections.reject}4495* @category Collection4496* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.4497* @param {number} limit - The maximum number of async operations at a time.4498* @param {Function} iteratee - An async truth test to apply to each item in4499* `coll`.4500* The should complete with a boolean value as its `result`.4501* Invoked with (item, callback).4502* @param {Function} [callback] - A callback which is called after all the4503* `iteratee` functions have finished. Invoked with (err, results).4504* @returns {Promise} a promise, if no callback is passed4505*/4506function rejectLimit (coll, limit, iteratee, callback) {4507return reject(eachOfLimit(limit), coll, iteratee, callback)4508}4509var rejectLimit$1 = awaitify(rejectLimit, 4);45104511/**4512* The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.4513*4514* @name rejectSeries4515* @static4516* @memberOf module:Collections4517* @method4518* @see [async.reject]{@link module:Collections.reject}4519* @category Collection4520* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.4521* @param {Function} iteratee - An async truth test to apply to each item in4522* `coll`.4523* The should complete with a boolean value as its `result`.4524* Invoked with (item, callback).4525* @param {Function} [callback] - A callback which is called after all the4526* `iteratee` functions have finished. Invoked with (err, results).4527* @returns {Promise} a promise, if no callback is passed4528*/4529function rejectSeries (coll, iteratee, callback) {4530return reject(eachOfSeries$1, coll, iteratee, callback)4531}4532var rejectSeries$1 = awaitify(rejectSeries, 3);45334534function constant$1(value) {4535return function () {4536return value;4537}4538}45394540/**4541* Attempts to get a successful response from `task` no more than `times` times4542* before returning an error. If the task is successful, the `callback` will be4543* passed the result of the successful task. If all attempts fail, the callback4544* will be passed the error and result (if any) of the final attempt.4545*4546* @name retry4547* @static4548* @memberOf module:ControlFlow4549* @method4550* @category Control Flow4551* @see [async.retryable]{@link module:ControlFlow.retryable}4552* @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an4553* object with `times` and `interval` or a number.4554* * `times` - The number of attempts to make before giving up. The default4555* is `5`.4556* * `interval` - The time to wait between retries, in milliseconds. The4557* default is `0`. The interval may also be specified as a function of the4558* retry count (see example).4559* * `errorFilter` - An optional synchronous function that is invoked on4560* erroneous result. If it returns `true` the retry attempts will continue;4561* if the function returns `false` the retry flow is aborted with the current4562* attempt's error and result being returned to the final callback.4563* Invoked with (err).4564* * If `opts` is a number, the number specifies the number of times to retry,4565* with the default interval of `0`.4566* @param {AsyncFunction} task - An async function to retry.4567* Invoked with (callback).4568* @param {Function} [callback] - An optional callback which is called when the4569* task has succeeded, or after the final failed attempt. It receives the `err`4570* and `result` arguments of the last attempt at completing the `task`. Invoked4571* with (err, results).4572* @returns {Promise} a promise if no callback provided4573*4574* @example4575*4576* // The `retry` function can be used as a stand-alone control flow by passing4577* // a callback, as shown below:4578*4579* // try calling apiMethod 3 times4580* async.retry(3, apiMethod, function(err, result) {4581* // do something with the result4582* });4583*4584* // try calling apiMethod 3 times, waiting 200 ms between each retry4585* async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {4586* // do something with the result4587* });4588*4589* // try calling apiMethod 10 times with exponential backoff4590* // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)4591* async.retry({4592* times: 10,4593* interval: function(retryCount) {4594* return 50 * Math.pow(2, retryCount);4595* }4596* }, apiMethod, function(err, result) {4597* // do something with the result4598* });4599*4600* // try calling apiMethod the default 5 times no delay between each retry4601* async.retry(apiMethod, function(err, result) {4602* // do something with the result4603* });4604*4605* // try calling apiMethod only when error condition satisfies, all other4606* // errors will abort the retry control flow and return to final callback4607* async.retry({4608* errorFilter: function(err) {4609* return err.message === 'Temporary error'; // only retry on a specific error4610* }4611* }, apiMethod, function(err, result) {4612* // do something with the result4613* });4614*4615* // to retry individual methods that are not as reliable within other4616* // control flow functions, use the `retryable` wrapper:4617* async.auto({4618* users: api.getUsers.bind(api),4619* payments: async.retryable(3, api.getPayments.bind(api))4620* }, function(err, results) {4621* // do something with the results4622* });4623*4624*/4625const DEFAULT_TIMES = 5;4626const DEFAULT_INTERVAL = 0;46274628function retry(opts, task, callback) {4629var options = {4630times: DEFAULT_TIMES,4631intervalFunc: constant$1(DEFAULT_INTERVAL)4632};46334634if (arguments.length < 3 && typeof opts === 'function') {4635callback = task || promiseCallback();4636task = opts;4637} else {4638parseTimes(options, opts);4639callback = callback || promiseCallback();4640}46414642if (typeof task !== 'function') {4643throw new Error("Invalid arguments for async.retry");4644}46454646var _task = wrapAsync(task);46474648var attempt = 1;4649function retryAttempt() {4650_task((err, ...args) => {4651if (err === false) return4652if (err && attempt++ < options.times &&4653(typeof options.errorFilter != 'function' ||4654options.errorFilter(err))) {4655setTimeout(retryAttempt, options.intervalFunc(attempt - 1));4656} else {4657callback(err, ...args);4658}4659});4660}46614662retryAttempt();4663return callback[PROMISE_SYMBOL]4664}46654666function parseTimes(acc, t) {4667if (typeof t === 'object') {4668acc.times = +t.times || DEFAULT_TIMES;46694670acc.intervalFunc = typeof t.interval === 'function' ?4671t.interval :4672constant$1(+t.interval || DEFAULT_INTERVAL);46734674acc.errorFilter = t.errorFilter;4675} else if (typeof t === 'number' || typeof t === 'string') {4676acc.times = +t || DEFAULT_TIMES;4677} else {4678throw new Error("Invalid arguments for async.retry");4679}4680}46814682/**4683* A close relative of [`retry`]{@link module:ControlFlow.retry}. This method4684* wraps a task and makes it retryable, rather than immediately calling it4685* with retries.4686*4687* @name retryable4688* @static4689* @memberOf module:ControlFlow4690* @method4691* @see [async.retry]{@link module:ControlFlow.retry}4692* @category Control Flow4693* @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional4694* options, exactly the same as from `retry`, except for a `opts.arity` that4695* is the arity of the `task` function, defaulting to `task.length`4696* @param {AsyncFunction} task - the asynchronous function to wrap.4697* This function will be passed any arguments passed to the returned wrapper.4698* Invoked with (...args, callback).4699* @returns {AsyncFunction} The wrapped function, which when invoked, will4700* retry on an error, based on the parameters specified in `opts`.4701* This function will accept the same parameters as `task`.4702* @example4703*4704* async.auto({4705* dep1: async.retryable(3, getFromFlakyService),4706* process: ["dep1", async.retryable(3, function (results, cb) {4707* maybeProcessData(results.dep1, cb);4708* })]4709* }, callback);4710*/4711function retryable (opts, task) {4712if (!task) {4713task = opts;4714opts = null;4715}4716let arity = (opts && opts.arity) || task.length;4717if (isAsync(task)) {4718arity += 1;4719}4720var _task = wrapAsync(task);4721return initialParams((args, callback) => {4722if (args.length < arity - 1 || callback == null) {4723args.push(callback);4724callback = promiseCallback();4725}4726function taskFn(cb) {4727_task(...args, cb);4728}47294730if (opts) retry(opts, taskFn, callback);4731else retry(taskFn, callback);47324733return callback[PROMISE_SYMBOL]4734});4735}47364737/**4738* Run the functions in the `tasks` collection in series, each one running once4739* the previous function has completed. If any functions in the series pass an4740* error to its callback, no more functions are run, and `callback` is4741* immediately called with the value of the error. Otherwise, `callback`4742* receives an array of results when `tasks` have completed.4743*4744* It is also possible to use an object instead of an array. Each property will4745* be run as a function, and the results will be passed to the final `callback`4746* as an object instead of an array. This can be a more readable way of handling4747* results from {@link async.series}.4748*4749* **Note** that while many implementations preserve the order of object4750* properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)4751* explicitly states that4752*4753* > The mechanics and order of enumerating the properties is not specified.4754*4755* So if you rely on the order in which your series of functions are executed,4756* and want this to work on all platforms, consider using an array.4757*4758* @name series4759* @static4760* @memberOf module:ControlFlow4761* @method4762* @category Control Flow4763* @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing4764* [async functions]{@link AsyncFunction} to run in series.4765* Each function can complete with any number of optional `result` values.4766* @param {Function} [callback] - An optional callback to run once all the4767* functions have completed. This function gets a results array (or object)4768* containing all the result arguments passed to the `task` callbacks. Invoked4769* with (err, result).4770* @return {Promise} a promise, if no callback is passed4771* @example4772*4773* //Using Callbacks4774* async.series([4775* function(callback) {4776* setTimeout(function() {4777* // do some async task4778* callback(null, 'one');4779* }, 200);4780* },4781* function(callback) {4782* setTimeout(function() {4783* // then do another async task4784* callback(null, 'two');4785* }, 100);4786* }4787* ], function(err, results) {4788* console.log(results);4789* // results is equal to ['one','two']4790* });4791*4792* // an example using objects instead of arrays4793* async.series({4794* one: function(callback) {4795* setTimeout(function() {4796* // do some async task4797* callback(null, 1);4798* }, 200);4799* },4800* two: function(callback) {4801* setTimeout(function() {4802* // then do another async task4803* callback(null, 2);4804* }, 100);4805* }4806* }, function(err, results) {4807* console.log(results);4808* // results is equal to: { one: 1, two: 2 }4809* });4810*4811* //Using Promises4812* async.series([4813* function(callback) {4814* setTimeout(function() {4815* callback(null, 'one');4816* }, 200);4817* },4818* function(callback) {4819* setTimeout(function() {4820* callback(null, 'two');4821* }, 100);4822* }4823* ]).then(results => {4824* console.log(results);4825* // results is equal to ['one','two']4826* }).catch(err => {4827* console.log(err);4828* });4829*4830* // an example using an object instead of an array4831* async.series({4832* one: function(callback) {4833* setTimeout(function() {4834* // do some async task4835* callback(null, 1);4836* }, 200);4837* },4838* two: function(callback) {4839* setTimeout(function() {4840* // then do another async task4841* callback(null, 2);4842* }, 100);4843* }4844* }).then(results => {4845* console.log(results);4846* // results is equal to: { one: 1, two: 2 }4847* }).catch(err => {4848* console.log(err);4849* });4850*4851* //Using async/await4852* async () => {4853* try {4854* let results = await async.series([4855* function(callback) {4856* setTimeout(function() {4857* // do some async task4858* callback(null, 'one');4859* }, 200);4860* },4861* function(callback) {4862* setTimeout(function() {4863* // then do another async task4864* callback(null, 'two');4865* }, 100);4866* }4867* ]);4868* console.log(results);4869* // results is equal to ['one','two']4870* }4871* catch (err) {4872* console.log(err);4873* }4874* }4875*4876* // an example using an object instead of an array4877* async () => {4878* try {4879* let results = await async.parallel({4880* one: function(callback) {4881* setTimeout(function() {4882* // do some async task4883* callback(null, 1);4884* }, 200);4885* },4886* two: function(callback) {4887* setTimeout(function() {4888* // then do another async task4889* callback(null, 2);4890* }, 100);4891* }4892* });4893* console.log(results);4894* // results is equal to: { one: 1, two: 2 }4895* }4896* catch (err) {4897* console.log(err);4898* }4899* }4900*4901*/4902function series(tasks, callback) {4903return parallel(eachOfSeries$1, tasks, callback);4904}49054906/**4907* Returns `true` if at least one element in the `coll` satisfies an async test.4908* If any iteratee call returns `true`, the main `callback` is immediately4909* called.4910*4911* @name some4912* @static4913* @memberOf module:Collections4914* @method4915* @alias any4916* @category Collection4917* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.4918* @param {AsyncFunction} iteratee - An async truth test to apply to each item4919* in the collections in parallel.4920* The iteratee should complete with a boolean `result` value.4921* Invoked with (item, callback).4922* @param {Function} [callback] - A callback which is called as soon as any4923* iteratee returns `true`, or after all the iteratee functions have finished.4924* Result will be either `true` or `false` depending on the values of the async4925* tests. Invoked with (err, result).4926* @returns {Promise} a promise, if no callback provided4927* @example4928*4929* // dir1 is a directory that contains file1.txt, file2.txt4930* // dir2 is a directory that contains file3.txt, file4.txt4931* // dir3 is a directory that contains file5.txt4932* // dir4 does not exist4933*4934* // asynchronous function that checks if a file exists4935* function fileExists(file, callback) {4936* fs.access(file, fs.constants.F_OK, (err) => {4937* callback(null, !err);4938* });4939* }4940*4941* // Using callbacks4942* async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,4943* function(err, result) {4944* console.log(result);4945* // true4946* // result is true since some file in the list exists4947* }4948*);4949*4950* async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,4951* function(err, result) {4952* console.log(result);4953* // false4954* // result is false since none of the files exists4955* }4956*);4957*4958* // Using Promises4959* async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)4960* .then( result => {4961* console.log(result);4962* // true4963* // result is true since some file in the list exists4964* }).catch( err => {4965* console.log(err);4966* });4967*4968* async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)4969* .then( result => {4970* console.log(result);4971* // false4972* // result is false since none of the files exists4973* }).catch( err => {4974* console.log(err);4975* });4976*4977* // Using async/await4978* async () => {4979* try {4980* let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);4981* console.log(result);4982* // true4983* // result is true since some file in the list exists4984* }4985* catch (err) {4986* console.log(err);4987* }4988* }4989*4990* async () => {4991* try {4992* let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);4993* console.log(result);4994* // false4995* // result is false since none of the files exists4996* }4997* catch (err) {4998* console.log(err);4999* }5000* }5001*5002*/5003function some(coll, iteratee, callback) {5004return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback)5005}5006var some$1 = awaitify(some, 3);50075008/**5009* The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.5010*5011* @name someLimit5012* @static5013* @memberOf module:Collections5014* @method5015* @see [async.some]{@link module:Collections.some}5016* @alias anyLimit5017* @category Collection5018* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.5019* @param {number} limit - The maximum number of async operations at a time.5020* @param {AsyncFunction} iteratee - An async truth test to apply to each item5021* in the collections in parallel.5022* The iteratee should complete with a boolean `result` value.5023* Invoked with (item, callback).5024* @param {Function} [callback] - A callback which is called as soon as any5025* iteratee returns `true`, or after all the iteratee functions have finished.5026* Result will be either `true` or `false` depending on the values of the async5027* tests. Invoked with (err, result).5028* @returns {Promise} a promise, if no callback provided5029*/5030function someLimit(coll, limit, iteratee, callback) {5031return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback)5032}5033var someLimit$1 = awaitify(someLimit, 4);50345035/**5036* The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.5037*5038* @name someSeries5039* @static5040* @memberOf module:Collections5041* @method5042* @see [async.some]{@link module:Collections.some}5043* @alias anySeries5044* @category Collection5045* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.5046* @param {AsyncFunction} iteratee - An async truth test to apply to each item5047* in the collections in series.5048* The iteratee should complete with a boolean `result` value.5049* Invoked with (item, callback).5050* @param {Function} [callback] - A callback which is called as soon as any5051* iteratee returns `true`, or after all the iteratee functions have finished.5052* Result will be either `true` or `false` depending on the values of the async5053* tests. Invoked with (err, result).5054* @returns {Promise} a promise, if no callback provided5055*/5056function someSeries(coll, iteratee, callback) {5057return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback)5058}5059var someSeries$1 = awaitify(someSeries, 3);50605061/**5062* Sorts a list by the results of running each `coll` value through an async5063* `iteratee`.5064*5065* @name sortBy5066* @static5067* @memberOf module:Collections5068* @method5069* @category Collection5070* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.5071* @param {AsyncFunction} iteratee - An async function to apply to each item in5072* `coll`.5073* The iteratee should complete with a value to use as the sort criteria as5074* its `result`.5075* Invoked with (item, callback).5076* @param {Function} callback - A callback which is called after all the5077* `iteratee` functions have finished, or an error occurs. Results is the items5078* from the original `coll` sorted by the values returned by the `iteratee`5079* calls. Invoked with (err, results).5080* @returns {Promise} a promise, if no callback passed5081* @example5082*5083* // bigfile.txt is a file that is 251100 bytes in size5084* // mediumfile.txt is a file that is 11000 bytes in size5085* // smallfile.txt is a file that is 121 bytes in size5086*5087* // asynchronous function that returns the file size in bytes5088* function getFileSizeInBytes(file, callback) {5089* fs.stat(file, function(err, stat) {5090* if (err) {5091* return callback(err);5092* }5093* callback(null, stat.size);5094* });5095* }5096*5097* // Using callbacks5098* async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes,5099* function(err, results) {5100* if (err) {5101* console.log(err);5102* } else {5103* console.log(results);5104* // results is now the original array of files sorted by5105* // file size (ascending by default), e.g.5106* // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']5107* }5108* }5109* );5110*5111* // By modifying the callback parameter the5112* // sorting order can be influenced:5113*5114* // ascending order5115* async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) {5116* getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {5117* if (getFileSizeErr) return callback(getFileSizeErr);5118* callback(null, fileSize);5119* });5120* }, function(err, results) {5121* if (err) {5122* console.log(err);5123* } else {5124* console.log(results);5125* // results is now the original array of files sorted by5126* // file size (ascending by default), e.g.5127* // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']5128* }5129* }5130* );5131*5132* // descending order5133* async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) {5134* getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {5135* if (getFileSizeErr) {5136* return callback(getFileSizeErr);5137* }5138* callback(null, fileSize * -1);5139* });5140* }, function(err, results) {5141* if (err) {5142* console.log(err);5143* } else {5144* console.log(results);5145* // results is now the original array of files sorted by5146* // file size (ascending by default), e.g.5147* // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt']5148* }5149* }5150* );5151*5152* // Error handling5153* async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes,5154* function(err, results) {5155* if (err) {5156* console.log(err);5157* // [ Error: ENOENT: no such file or directory ]5158* } else {5159* console.log(results);5160* }5161* }5162* );5163*5164* // Using Promises5165* async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes)5166* .then( results => {5167* console.log(results);5168* // results is now the original array of files sorted by5169* // file size (ascending by default), e.g.5170* // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']5171* }).catch( err => {5172* console.log(err);5173* });5174*5175* // Error handling5176* async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes)5177* .then( results => {5178* console.log(results);5179* }).catch( err => {5180* console.log(err);5181* // [ Error: ENOENT: no such file or directory ]5182* });5183*5184* // Using async/await5185* (async () => {5186* try {5187* let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);5188* console.log(results);5189* // results is now the original array of files sorted by5190* // file size (ascending by default), e.g.5191* // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']5192* }5193* catch (err) {5194* console.log(err);5195* }5196* })();5197*5198* // Error handling5199* async () => {5200* try {5201* let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);5202* console.log(results);5203* }5204* catch (err) {5205* console.log(err);5206* // [ Error: ENOENT: no such file or directory ]5207* }5208* }5209*5210*/5211function sortBy (coll, iteratee, callback) {5212var _iteratee = wrapAsync(iteratee);5213return map$1(coll, (x, iterCb) => {5214_iteratee(x, (err, criteria) => {5215if (err) return iterCb(err);5216iterCb(err, {value: x, criteria});5217});5218}, (err, results) => {5219if (err) return callback(err);5220callback(null, results.sort(comparator).map(v => v.value));5221});52225223function comparator(left, right) {5224var a = left.criteria, b = right.criteria;5225return a < b ? -1 : a > b ? 1 : 0;5226}5227}5228var sortBy$1 = awaitify(sortBy, 3);52295230/**5231* Sets a time limit on an asynchronous function. If the function does not call5232* its callback within the specified milliseconds, it will be called with a5233* timeout error. The code property for the error object will be `'ETIMEDOUT'`.5234*5235* @name timeout5236* @static5237* @memberOf module:Utils5238* @method5239* @category Util5240* @param {AsyncFunction} asyncFn - The async function to limit in time.5241* @param {number} milliseconds - The specified time limit.5242* @param {*} [info] - Any variable you want attached (`string`, `object`, etc)5243* to timeout Error for more information..5244* @returns {AsyncFunction} Returns a wrapped function that can be used with any5245* of the control flow functions.5246* Invoke this function with the same parameters as you would `asyncFunc`.5247* @example5248*5249* function myFunction(foo, callback) {5250* doAsyncTask(foo, function(err, data) {5251* // handle errors5252* if (err) return callback(err);5253*5254* // do some stuff ...5255*5256* // return processed data5257* return callback(null, data);5258* });5259* }5260*5261* var wrapped = async.timeout(myFunction, 1000);5262*5263* // call `wrapped` as you would `myFunction`5264* wrapped({ bar: 'bar' }, function(err, data) {5265* // if `myFunction` takes < 1000 ms to execute, `err`5266* // and `data` will have their expected values5267*5268* // else `err` will be an Error with the code 'ETIMEDOUT'5269* });5270*/5271function timeout(asyncFn, milliseconds, info) {5272var fn = wrapAsync(asyncFn);52735274return initialParams((args, callback) => {5275var timedOut = false;5276var timer;52775278function timeoutCallback() {5279var name = asyncFn.name || 'anonymous';5280var error = new Error('Callback function "' + name + '" timed out.');5281error.code = 'ETIMEDOUT';5282if (info) {5283error.info = info;5284}5285timedOut = true;5286callback(error);5287}52885289args.push((...cbArgs) => {5290if (!timedOut) {5291callback(...cbArgs);5292clearTimeout(timer);5293}5294});52955296// setup timer and call original function5297timer = setTimeout(timeoutCallback, milliseconds);5298fn(...args);5299});5300}53015302function range(size) {5303var result = Array(size);5304while (size--) {5305result[size] = size;5306}5307return result;5308}53095310/**5311* The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a5312* time.5313*5314* @name timesLimit5315* @static5316* @memberOf module:ControlFlow5317* @method5318* @see [async.times]{@link module:ControlFlow.times}5319* @category Control Flow5320* @param {number} count - The number of times to run the function.5321* @param {number} limit - The maximum number of async operations at a time.5322* @param {AsyncFunction} iteratee - The async function to call `n` times.5323* Invoked with the iteration index and a callback: (n, next).5324* @param {Function} callback - see [async.map]{@link module:Collections.map}.5325* @returns {Promise} a promise, if no callback is provided5326*/5327function timesLimit(count, limit, iteratee, callback) {5328var _iteratee = wrapAsync(iteratee);5329return mapLimit$1(range(count), limit, _iteratee, callback);5330}53315332/**5333* Calls the `iteratee` function `n` times, and accumulates results in the same5334* manner you would use with [map]{@link module:Collections.map}.5335*5336* @name times5337* @static5338* @memberOf module:ControlFlow5339* @method5340* @see [async.map]{@link module:Collections.map}5341* @category Control Flow5342* @param {number} n - The number of times to run the function.5343* @param {AsyncFunction} iteratee - The async function to call `n` times.5344* Invoked with the iteration index and a callback: (n, next).5345* @param {Function} callback - see {@link module:Collections.map}.5346* @returns {Promise} a promise, if no callback is provided5347* @example5348*5349* // Pretend this is some complicated async factory5350* var createUser = function(id, callback) {5351* callback(null, {5352* id: 'user' + id5353* });5354* };5355*5356* // generate 5 users5357* async.times(5, function(n, next) {5358* createUser(n, function(err, user) {5359* next(err, user);5360* });5361* }, function(err, users) {5362* // we should now have 5 users5363* });5364*/5365function times (n, iteratee, callback) {5366return timesLimit(n, Infinity, iteratee, callback)5367}53685369/**5370* The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.5371*5372* @name timesSeries5373* @static5374* @memberOf module:ControlFlow5375* @method5376* @see [async.times]{@link module:ControlFlow.times}5377* @category Control Flow5378* @param {number} n - The number of times to run the function.5379* @param {AsyncFunction} iteratee - The async function to call `n` times.5380* Invoked with the iteration index and a callback: (n, next).5381* @param {Function} callback - see {@link module:Collections.map}.5382* @returns {Promise} a promise, if no callback is provided5383*/5384function timesSeries (n, iteratee, callback) {5385return timesLimit(n, 1, iteratee, callback)5386}53875388/**5389* A relative of `reduce`. Takes an Object or Array, and iterates over each5390* element in parallel, each step potentially mutating an `accumulator` value.5391* The type of the accumulator defaults to the type of collection passed in.5392*5393* @name transform5394* @static5395* @memberOf module:Collections5396* @method5397* @category Collection5398* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.5399* @param {*} [accumulator] - The initial state of the transform. If omitted,5400* it will default to an empty Object or Array, depending on the type of `coll`5401* @param {AsyncFunction} iteratee - A function applied to each item in the5402* collection that potentially modifies the accumulator.5403* Invoked with (accumulator, item, key, callback).5404* @param {Function} [callback] - A callback which is called after all the5405* `iteratee` functions have finished. Result is the transformed accumulator.5406* Invoked with (err, result).5407* @returns {Promise} a promise, if no callback provided5408* @example5409*5410* // file1.txt is a file that is 1000 bytes in size5411* // file2.txt is a file that is 2000 bytes in size5412* // file3.txt is a file that is 3000 bytes in size5413*5414* // helper function that returns human-readable size format from bytes5415* function formatBytes(bytes, decimals = 2) {5416* // implementation not included for brevity5417* return humanReadbleFilesize;5418* }5419*5420* const fileList = ['file1.txt','file2.txt','file3.txt'];5421*5422* // asynchronous function that returns the file size, transformed to human-readable format5423* // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.5424* function transformFileSize(acc, value, key, callback) {5425* fs.stat(value, function(err, stat) {5426* if (err) {5427* return callback(err);5428* }5429* acc[key] = formatBytes(stat.size);5430* callback(null);5431* });5432* }5433*5434* // Using callbacks5435* async.transform(fileList, transformFileSize, function(err, result) {5436* if(err) {5437* console.log(err);5438* } else {5439* console.log(result);5440* // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]5441* }5442* });5443*5444* // Using Promises5445* async.transform(fileList, transformFileSize)5446* .then(result => {5447* console.log(result);5448* // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]5449* }).catch(err => {5450* console.log(err);5451* });5452*5453* // Using async/await5454* (async () => {5455* try {5456* let result = await async.transform(fileList, transformFileSize);5457* console.log(result);5458* // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]5459* }5460* catch (err) {5461* console.log(err);5462* }5463* })();5464*5465* @example5466*5467* // file1.txt is a file that is 1000 bytes in size5468* // file2.txt is a file that is 2000 bytes in size5469* // file3.txt is a file that is 3000 bytes in size5470*5471* // helper function that returns human-readable size format from bytes5472* function formatBytes(bytes, decimals = 2) {5473* // implementation not included for brevity5474* return humanReadbleFilesize;5475* }5476*5477* const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' };5478*5479* // asynchronous function that returns the file size, transformed to human-readable format5480* // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.5481* function transformFileSize(acc, value, key, callback) {5482* fs.stat(value, function(err, stat) {5483* if (err) {5484* return callback(err);5485* }5486* acc[key] = formatBytes(stat.size);5487* callback(null);5488* });5489* }5490*5491* // Using callbacks5492* async.transform(fileMap, transformFileSize, function(err, result) {5493* if(err) {5494* console.log(err);5495* } else {5496* console.log(result);5497* // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }5498* }5499* });5500*5501* // Using Promises5502* async.transform(fileMap, transformFileSize)5503* .then(result => {5504* console.log(result);5505* // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }5506* }).catch(err => {5507* console.log(err);5508* });5509*5510* // Using async/await5511* async () => {5512* try {5513* let result = await async.transform(fileMap, transformFileSize);5514* console.log(result);5515* // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }5516* }5517* catch (err) {5518* console.log(err);5519* }5520* }5521*5522*/5523function transform (coll, accumulator, iteratee, callback) {5524if (arguments.length <= 3 && typeof accumulator === 'function') {5525callback = iteratee;5526iteratee = accumulator;5527accumulator = Array.isArray(coll) ? [] : {};5528}5529callback = once(callback || promiseCallback());5530var _iteratee = wrapAsync(iteratee);55315532eachOf$1(coll, (v, k, cb) => {5533_iteratee(accumulator, v, k, cb);5534}, err => callback(err, accumulator));5535return callback[PROMISE_SYMBOL]5536}55375538/**5539* It runs each task in series but stops whenever any of the functions were5540* successful. If one of the tasks were successful, the `callback` will be5541* passed the result of the successful task. If all tasks fail, the callback5542* will be passed the error and result (if any) of the final attempt.5543*5544* @name tryEach5545* @static5546* @memberOf module:ControlFlow5547* @method5548* @category Control Flow5549* @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to5550* run, each function is passed a `callback(err, result)` it must call on5551* completion with an error `err` (which can be `null`) and an optional `result`5552* value.5553* @param {Function} [callback] - An optional callback which is called when one5554* of the tasks has succeeded, or all have failed. It receives the `err` and5555* `result` arguments of the last attempt at completing the `task`. Invoked with5556* (err, results).5557* @returns {Promise} a promise, if no callback is passed5558* @example5559* async.tryEach([5560* function getDataFromFirstWebsite(callback) {5561* // Try getting the data from the first website5562* callback(err, data);5563* },5564* function getDataFromSecondWebsite(callback) {5565* // First website failed,5566* // Try getting the data from the backup website5567* callback(err, data);5568* }5569* ],5570* // optional callback5571* function(err, results) {5572* Now do something with the data.5573* });5574*5575*/5576function tryEach(tasks, callback) {5577var error = null;5578var result;5579return eachSeries$1(tasks, (task, taskCb) => {5580wrapAsync(task)((err, ...args) => {5581if (err === false) return taskCb(err);55825583if (args.length < 2) {5584[result] = args;5585} else {5586result = args;5587}5588error = err;5589taskCb(err ? null : {});5590});5591}, () => callback(error, result));5592}55935594var tryEach$1 = awaitify(tryEach);55955596/**5597* Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,5598* unmemoized form. Handy for testing.5599*5600* @name unmemoize5601* @static5602* @memberOf module:Utils5603* @method5604* @see [async.memoize]{@link module:Utils.memoize}5605* @category Util5606* @param {AsyncFunction} fn - the memoized function5607* @returns {AsyncFunction} a function that calls the original unmemoized function5608*/5609function unmemoize(fn) {5610return (...args) => {5611return (fn.unmemoized || fn)(...args);5612};5613}56145615/**5616* Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when5617* stopped, or an error occurs.5618*5619* @name whilst5620* @static5621* @memberOf module:ControlFlow5622* @method5623* @category Control Flow5624* @param {AsyncFunction} test - asynchronous truth test to perform before each5625* execution of `iteratee`. Invoked with ().5626* @param {AsyncFunction} iteratee - An async function which is called each time5627* `test` passes. Invoked with (callback).5628* @param {Function} [callback] - A callback which is called after the test5629* function has failed and repeated execution of `iteratee` has stopped. `callback`5630* will be passed an error and any arguments passed to the final `iteratee`'s5631* callback. Invoked with (err, [results]);5632* @returns {Promise} a promise, if no callback is passed5633* @example5634*5635* var count = 0;5636* async.whilst(5637* function test(cb) { cb(null, count < 5); },5638* function iter(callback) {5639* count++;5640* setTimeout(function() {5641* callback(null, count);5642* }, 1000);5643* },5644* function (err, n) {5645* // 5 seconds have passed, n = 55646* }5647* );5648*/5649function whilst(test, iteratee, callback) {5650callback = onlyOnce(callback);5651var _fn = wrapAsync(iteratee);5652var _test = wrapAsync(test);5653var results = [];56545655function next(err, ...rest) {5656if (err) return callback(err);5657results = rest;5658if (err === false) return;5659_test(check);5660}56615662function check(err, truth) {5663if (err) return callback(err);5664if (err === false) return;5665if (!truth) return callback(null, ...results);5666_fn(next);5667}56685669return _test(check);5670}5671var whilst$1 = awaitify(whilst, 3);56725673/**5674* Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when5675* stopped, or an error occurs. `callback` will be passed an error and any5676* arguments passed to the final `iteratee`'s callback.5677*5678* The inverse of [whilst]{@link module:ControlFlow.whilst}.5679*5680* @name until5681* @static5682* @memberOf module:ControlFlow5683* @method5684* @see [async.whilst]{@link module:ControlFlow.whilst}5685* @category Control Flow5686* @param {AsyncFunction} test - asynchronous truth test to perform before each5687* execution of `iteratee`. Invoked with (callback).5688* @param {AsyncFunction} iteratee - An async function which is called each time5689* `test` fails. Invoked with (callback).5690* @param {Function} [callback] - A callback which is called after the test5691* function has passed and repeated execution of `iteratee` has stopped. `callback`5692* will be passed an error and any arguments passed to the final `iteratee`'s5693* callback. Invoked with (err, [results]);5694* @returns {Promise} a promise, if a callback is not passed5695*5696* @example5697* const results = []5698* let finished = false5699* async.until(function test(cb) {5700* cb(null, finished)5701* }, function iter(next) {5702* fetchPage(url, (err, body) => {5703* if (err) return next(err)5704* results = results.concat(body.objects)5705* finished = !!body.next5706* next(err)5707* })5708* }, function done (err) {5709* // all pages have been fetched5710* })5711*/5712function until(test, iteratee, callback) {5713const _test = wrapAsync(test);5714return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback);5715}57165717/**5718* Runs the `tasks` array of functions in series, each passing their results to5719* the next in the array. However, if any of the `tasks` pass an error to their5720* own callback, the next function is not executed, and the main `callback` is5721* immediately called with the error.5722*5723* @name waterfall5724* @static5725* @memberOf module:ControlFlow5726* @method5727* @category Control Flow5728* @param {Array} tasks - An array of [async functions]{@link AsyncFunction}5729* to run.5730* Each function should complete with any number of `result` values.5731* The `result` values will be passed as arguments, in order, to the next task.5732* @param {Function} [callback] - An optional callback to run once all the5733* functions have completed. This will be passed the results of the last task's5734* callback. Invoked with (err, [results]).5735* @returns {Promise} a promise, if a callback is omitted5736* @example5737*5738* async.waterfall([5739* function(callback) {5740* callback(null, 'one', 'two');5741* },5742* function(arg1, arg2, callback) {5743* // arg1 now equals 'one' and arg2 now equals 'two'5744* callback(null, 'three');5745* },5746* function(arg1, callback) {5747* // arg1 now equals 'three'5748* callback(null, 'done');5749* }5750* ], function (err, result) {5751* // result now equals 'done'5752* });5753*5754* // Or, with named functions:5755* async.waterfall([5756* myFirstFunction,5757* mySecondFunction,5758* myLastFunction,5759* ], function (err, result) {5760* // result now equals 'done'5761* });5762* function myFirstFunction(callback) {5763* callback(null, 'one', 'two');5764* }5765* function mySecondFunction(arg1, arg2, callback) {5766* // arg1 now equals 'one' and arg2 now equals 'two'5767* callback(null, 'three');5768* }5769* function myLastFunction(arg1, callback) {5770* // arg1 now equals 'three'5771* callback(null, 'done');5772* }5773*/5774function waterfall (tasks, callback) {5775callback = once(callback);5776if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));5777if (!tasks.length) return callback();5778var taskIndex = 0;57795780function nextTask(args) {5781var task = wrapAsync(tasks[taskIndex++]);5782task(...args, onlyOnce(next));5783}57845785function next(err, ...args) {5786if (err === false) return5787if (err || taskIndex === tasks.length) {5788return callback(err, ...args);5789}5790nextTask(args);5791}57925793nextTask([]);5794}57955796var waterfall$1 = awaitify(waterfall);57975798/**5799* An "async function" in the context of Async is an asynchronous function with5800* a variable number of parameters, with the final parameter being a callback.5801* (`function (arg1, arg2, ..., callback) {}`)5802* The final callback is of the form `callback(err, results...)`, which must be5803* called once the function is completed. The callback should be called with a5804* Error as its first argument to signal that an error occurred.5805* Otherwise, if no error occurred, it should be called with `null` as the first5806* argument, and any additional `result` arguments that may apply, to signal5807* successful completion.5808* The callback must be called exactly once, ideally on a later tick of the5809* JavaScript event loop.5810*5811* This type of function is also referred to as a "Node-style async function",5812* or a "continuation passing-style function" (CPS). Most of the methods of this5813* library are themselves CPS/Node-style async functions, or functions that5814* return CPS/Node-style async functions.5815*5816* Wherever we accept a Node-style async function, we also directly accept an5817* [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.5818* In this case, the `async` function will not be passed a final callback5819* argument, and any thrown error will be used as the `err` argument of the5820* implicit callback, and the return value will be used as the `result` value.5821* (i.e. a `rejected` of the returned Promise becomes the `err` callback5822* argument, and a `resolved` value becomes the `result`.)5823*5824* Note, due to JavaScript limitations, we can only detect native `async`5825* functions and not transpilied implementations.5826* Your environment must have `async`/`await` support for this to work.5827* (e.g. Node > v7.6, or a recent version of a modern browser).5828* If you are using `async` functions through a transpiler (e.g. Babel), you5829* must still wrap the function with [asyncify]{@link module:Utils.asyncify},5830* because the `async function` will be compiled to an ordinary function that5831* returns a promise.5832*5833* @typedef {Function} AsyncFunction5834* @static5835*/58365837var index = {5838apply,5839applyEach: applyEach$1,5840applyEachSeries,5841asyncify,5842auto,5843autoInject,5844cargo,5845cargoQueue: cargo$1,5846compose,5847concat: concat$1,5848concatLimit: concatLimit$1,5849concatSeries: concatSeries$1,5850constant,5851detect: detect$1,5852detectLimit: detectLimit$1,5853detectSeries: detectSeries$1,5854dir,5855doUntil,5856doWhilst: doWhilst$1,5857each,5858eachLimit: eachLimit$2,5859eachOf: eachOf$1,5860eachOfLimit: eachOfLimit$2,5861eachOfSeries: eachOfSeries$1,5862eachSeries: eachSeries$1,5863ensureAsync,5864every: every$1,5865everyLimit: everyLimit$1,5866everySeries: everySeries$1,5867filter: filter$1,5868filterLimit: filterLimit$1,5869filterSeries: filterSeries$1,5870forever: forever$1,5871groupBy,5872groupByLimit: groupByLimit$1,5873groupBySeries,5874log,5875map: map$1,5876mapLimit: mapLimit$1,5877mapSeries: mapSeries$1,5878mapValues,5879mapValuesLimit: mapValuesLimit$1,5880mapValuesSeries,5881memoize,5882nextTick,5883parallel: parallel$1,5884parallelLimit,5885priorityQueue,5886queue: queue$1,5887race: race$1,5888reduce: reduce$1,5889reduceRight,5890reflect,5891reflectAll,5892reject: reject$2,5893rejectLimit: rejectLimit$1,5894rejectSeries: rejectSeries$1,5895retry,5896retryable,5897seq,5898series,5899setImmediate: setImmediate$1,5900some: some$1,5901someLimit: someLimit$1,5902someSeries: someSeries$1,5903sortBy: sortBy$1,5904timeout,5905times,5906timesLimit,5907timesSeries,5908transform,5909tryEach: tryEach$1,5910unmemoize,5911until,5912waterfall: waterfall$1,5913whilst: whilst$1,59145915// aliases5916all: every$1,5917allLimit: everyLimit$1,5918allSeries: everySeries$1,5919any: some$1,5920anyLimit: someLimit$1,5921anySeries: someSeries$1,5922find: detect$1,5923findLimit: detectLimit$1,5924findSeries: detectSeries$1,5925flatMap: concat$1,5926flatMapLimit: concatLimit$1,5927flatMapSeries: concatSeries$1,5928forEach: each,5929forEachSeries: eachSeries$1,5930forEachLimit: eachLimit$2,5931forEachOf: eachOf$1,5932forEachOfSeries: eachOfSeries$1,5933forEachOfLimit: eachOfLimit$2,5934inject: reduce$1,5935foldl: reduce$1,5936foldr: reduceRight,5937select: filter$1,5938selectLimit: filterLimit$1,5939selectSeries: filterSeries$1,5940wrapSync: asyncify,5941during: whilst$1,5942doDuring: doWhilst$15943};59445945export default index;5946export { apply, applyEach$1 as applyEach, applyEachSeries, asyncify, auto, autoInject, cargo, cargo$1 as cargoQueue, compose, concat$1 as concat, concatLimit$1 as concatLimit, concatSeries$1 as concatSeries, constant, detect$1 as detect, detectLimit$1 as detectLimit, detectSeries$1 as detectSeries, dir, doUntil, doWhilst$1 as doWhilst, each, eachLimit$2 as eachLimit, eachOf$1 as eachOf, eachOfLimit$2 as eachOfLimit, eachOfSeries$1 as eachOfSeries, eachSeries$1 as eachSeries, ensureAsync, every$1 as every, everyLimit$1 as everyLimit, everySeries$1 as everySeries, filter$1 as filter, filterLimit$1 as filterLimit, filterSeries$1 as filterSeries, forever$1 as forever, groupBy, groupByLimit$1 as groupByLimit, groupBySeries, log, map$1 as map, mapLimit$1 as mapLimit, mapSeries$1 as mapSeries, mapValues, mapValuesLimit$1 as mapValuesLimit, mapValuesSeries, memoize, nextTick, parallel$1 as parallel, parallelLimit, priorityQueue, queue$1 as queue, race$1 as race, reduce$1 as reduce, reduceRight, reflect, reflectAll, reject$2 as reject, rejectLimit$1 as rejectLimit, rejectSeries$1 as rejectSeries, retry, retryable, seq, series, setImmediate$1 as setImmediate, some$1 as some, someLimit$1 as someLimit, someSeries$1 as someSeries, sortBy$1 as sortBy, timeout, times, timesLimit, timesSeries, transform, tryEach$1 as tryEach, unmemoize, until, waterfall$1 as waterfall, whilst$1 as whilst, every$1 as all, everyLimit$1 as allLimit, everySeries$1 as allSeries, some$1 as any, someLimit$1 as anyLimit, someSeries$1 as anySeries, detect$1 as find, detectLimit$1 as findLimit, detectSeries$1 as findSeries, concat$1 as flatMap, concatLimit$1 as flatMapLimit, concatSeries$1 as flatMapSeries, each as forEach, eachSeries$1 as forEachSeries, eachLimit$2 as forEachLimit, eachOf$1 as forEachOf, eachOfSeries$1 as forEachOfSeries, eachOfLimit$2 as forEachOfLimit, reduce$1 as inject, reduce$1 as foldl, reduceRight as foldr, filter$1 as select, filterLimit$1 as selectLimit, filterSeries$1 as selectSeries, asyncify as wrapSync, whilst$1 as during, doWhilst$1 as doDuring };594759485949