(function (global, factory) {1typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :2typeof define === 'function' && define.amd ? define(['exports'], factory) :3(factory((global.async = {})));4}(this, (function (exports) { 'use strict';56/**7* Creates a continuation function with some arguments already applied.8*9* Useful as a shorthand when combined with other control flow functions. Any10* arguments passed to the returned function are added to the arguments11* originally passed to apply.12*13* @name apply14* @static15* @memberOf module:Utils16* @method17* @category Util18* @param {Function} fn - The function you want to eventually apply all19* arguments to. Invokes with (arguments...).20* @param {...*} arguments... - Any number of arguments to automatically apply21* when the continuation is called.22* @returns {Function} the partially-applied function23* @example24*25* // using apply26* async.parallel([27* async.apply(fs.writeFile, 'testfile1', 'test1'),28* async.apply(fs.writeFile, 'testfile2', 'test2')29* ]);30*31*32* // the same process without using apply33* async.parallel([34* function(callback) {35* fs.writeFile('testfile1', 'test1', callback);36* },37* function(callback) {38* fs.writeFile('testfile2', 'test2', callback);39* }40* ]);41*42* // It's possible to pass any number of additional arguments when calling the43* // continuation:44*45* node> var fn = async.apply(sys.puts, 'one');46* node> fn('two', 'three');47* one48* two49* three50*/51function apply(fn, ...args) {52return (...callArgs) => fn(...args,...callArgs);53}5455function initialParams (fn) {56return function (...args/*, callback*/) {57var callback = args.pop();58return fn.call(this, args, callback);59};60}6162/* istanbul ignore file */6364var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;65var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;66var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';6768function fallback(fn) {69setTimeout(fn, 0);70}7172function wrap(defer) {73return (fn, ...args) => defer(() => fn(...args));74}7576var _defer;7778if (hasQueueMicrotask) {79_defer = queueMicrotask;80} else if (hasSetImmediate) {81_defer = setImmediate;82} else if (hasNextTick) {83_defer = process.nextTick;84} else {85_defer = fallback;86}8788var setImmediate$1 = wrap(_defer);8990/**91* Take a sync function and make it async, passing its return value to a92* callback. This is useful for plugging sync functions into a waterfall,93* series, or other async functions. Any arguments passed to the generated94* function will be passed to the wrapped function (except for the final95* callback argument). Errors thrown will be passed to the callback.96*97* If the function passed to `asyncify` returns a Promise, that promises's98* resolved/rejected state will be used to call the callback, rather than simply99* the synchronous return value.100*101* This also means you can asyncify ES2017 `async` functions.102*103* @name asyncify104* @static105* @memberOf module:Utils106* @method107* @alias wrapSync108* @category Util109* @param {Function} func - The synchronous function, or Promise-returning110* function to convert to an {@link AsyncFunction}.111* @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be112* invoked with `(args..., callback)`.113* @example114*115* // passing a regular synchronous function116* async.waterfall([117* async.apply(fs.readFile, filename, "utf8"),118* async.asyncify(JSON.parse),119* function (data, next) {120* // data is the result of parsing the text.121* // If there was a parsing error, it would have been caught.122* }123* ], callback);124*125* // passing a function returning a promise126* async.waterfall([127* async.apply(fs.readFile, filename, "utf8"),128* async.asyncify(function (contents) {129* return db.model.create(contents);130* }),131* function (model, next) {132* // `model` is the instantiated model object.133* // If there was an error, this function would be skipped.134* }135* ], callback);136*137* // es2017 example, though `asyncify` is not needed if your JS environment138* // supports async functions out of the box139* var q = async.queue(async.asyncify(async function(file) {140* var intermediateStep = await processFile(file);141* return await somePromise(intermediateStep)142* }));143*144* q.push(files);145*/146function asyncify(func) {147if (isAsync(func)) {148return function (...args/*, callback*/) {149const callback = args.pop();150const promise = func.apply(this, args);151return handlePromise(promise, callback)152}153}154155return initialParams(function (args, callback) {156var result;157try {158result = func.apply(this, args);159} catch (e) {160return callback(e);161}162// if result is Promise object163if (result && typeof result.then === 'function') {164return handlePromise(result, callback)165} else {166callback(null, result);167}168});169}170171function handlePromise(promise, callback) {172return promise.then(value => {173invokeCallback(callback, null, value);174}, err => {175invokeCallback(callback, err && err.message ? err : new Error(err));176});177}178179function invokeCallback(callback, error, value) {180try {181callback(error, value);182} catch (err) {183setImmediate$1(e => { throw e }, err);184}185}186187function isAsync(fn) {188return fn[Symbol.toStringTag] === 'AsyncFunction';189}190191function isAsyncGenerator(fn) {192return fn[Symbol.toStringTag] === 'AsyncGenerator';193}194195function isAsyncIterable(obj) {196return typeof obj[Symbol.asyncIterator] === 'function';197}198199function wrapAsync(asyncFn) {200if (typeof asyncFn !== 'function') throw new Error('expected a function')201return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;202}203204// conditionally promisify a function.205// only return a promise if a callback is omitted206function awaitify (asyncFn, arity = asyncFn.length) {207if (!arity) throw new Error('arity is undefined')208function awaitable (...args) {209if (typeof args[arity - 1] === 'function') {210return asyncFn.apply(this, args)211}212213return new Promise((resolve, reject) => {214args[arity - 1] = (err, ...cbArgs) => {215if (err) return reject(err)216resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);217};218asyncFn.apply(this, args);219})220}221222return awaitable223}224225function applyEach (eachfn) {226return function applyEach(fns, ...callArgs) {227const go = awaitify(function (callback) {228var that = this;229return eachfn(fns, (fn, cb) => {230wrapAsync(fn).apply(that, callArgs.concat(cb));231}, callback);232});233return go;234};235}236237function _asyncMap(eachfn, arr, iteratee, callback) {238arr = arr || [];239var results = [];240var counter = 0;241var _iteratee = wrapAsync(iteratee);242243return eachfn(arr, (value, _, iterCb) => {244var index = counter++;245_iteratee(value, (err, v) => {246results[index] = v;247iterCb(err);248});249}, err => {250callback(err, results);251});252}253254function isArrayLike(value) {255return value &&256typeof value.length === 'number' &&257value.length >= 0 &&258value.length % 1 === 0;259}260261// A temporary value used to identify if the loop should be broken.262// See #1064, #1293263const breakLoop = {};264265function once(fn) {266function wrapper (...args) {267if (fn === null) return;268var callFn = fn;269fn = null;270callFn.apply(this, args);271}272Object.assign(wrapper, fn);273return wrapper274}275276function getIterator (coll) {277return coll[Symbol.iterator] && coll[Symbol.iterator]();278}279280function createArrayIterator(coll) {281var i = -1;282var len = coll.length;283return function next() {284return ++i < len ? {value: coll[i], key: i} : null;285}286}287288function createES2015Iterator(iterator) {289var i = -1;290return function next() {291var item = iterator.next();292if (item.done)293return null;294i++;295return {value: item.value, key: i};296}297}298299function createObjectIterator(obj) {300var okeys = obj ? Object.keys(obj) : [];301var i = -1;302var len = okeys.length;303return function next() {304var key = okeys[++i];305if (key === '__proto__') {306return next();307}308return i < len ? {value: obj[key], key} : null;309};310}311312function createIterator(coll) {313if (isArrayLike(coll)) {314return createArrayIterator(coll);315}316317var iterator = getIterator(coll);318return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);319}320321function onlyOnce(fn) {322return function (...args) {323if (fn === null) throw new Error("Callback was already called.");324var callFn = fn;325fn = null;326callFn.apply(this, args);327};328}329330// for async generators331function asyncEachOfLimit(generator, limit, iteratee, callback) {332let done = false;333let canceled = false;334let awaiting = false;335let running = 0;336let idx = 0;337338function replenish() {339//console.log('replenish')340if (running >= limit || awaiting || done) return341//console.log('replenish awaiting')342awaiting = true;343generator.next().then(({value, done: iterDone}) => {344//console.log('got value', value)345if (canceled || done) return346awaiting = false;347if (iterDone) {348done = true;349if (running <= 0) {350//console.log('done nextCb')351callback(null);352}353return;354}355running++;356iteratee(value, idx, iterateeCallback);357idx++;358replenish();359}).catch(handleError);360}361362function iterateeCallback(err, result) {363//console.log('iterateeCallback')364running -= 1;365if (canceled) return366if (err) return handleError(err)367368if (err === false) {369done = true;370canceled = true;371return372}373374if (result === breakLoop || (done && running <= 0)) {375done = true;376//console.log('done iterCb')377return callback(null);378}379replenish();380}381382function handleError(err) {383if (canceled) return384awaiting = false;385done = true;386callback(err);387}388389replenish();390}391392var eachOfLimit = (limit) => {393return (obj, iteratee, callback) => {394callback = once(callback);395if (limit <= 0) {396throw new RangeError('concurrency limit cannot be less than 1')397}398if (!obj) {399return callback(null);400}401if (isAsyncGenerator(obj)) {402return asyncEachOfLimit(obj, limit, iteratee, callback)403}404if (isAsyncIterable(obj)) {405return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback)406}407var nextElem = createIterator(obj);408var done = false;409var canceled = false;410var running = 0;411var looping = false;412413function iterateeCallback(err, value) {414if (canceled) return415running -= 1;416if (err) {417done = true;418callback(err);419}420else if (err === false) {421done = true;422canceled = true;423}424else if (value === breakLoop || (done && running <= 0)) {425done = true;426return callback(null);427}428else if (!looping) {429replenish();430}431}432433function replenish () {434looping = true;435while (running < limit && !done) {436var elem = nextElem();437if (elem === null) {438done = true;439if (running <= 0) {440callback(null);441}442return;443}444running += 1;445iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));446}447looping = false;448}449450replenish();451};452};453454/**455* The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a456* time.457*458* @name eachOfLimit459* @static460* @memberOf module:Collections461* @method462* @see [async.eachOf]{@link module:Collections.eachOf}463* @alias forEachOfLimit464* @category Collection465* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.466* @param {number} limit - The maximum number of async operations at a time.467* @param {AsyncFunction} iteratee - An async function to apply to each468* item in `coll`. The `key` is the item's key, or index in the case of an469* array.470* Invoked with (item, key, callback).471* @param {Function} [callback] - A callback which is called when all472* `iteratee` functions have finished, or an error occurs. Invoked with (err).473* @returns {Promise} a promise, if a callback is omitted474*/475function eachOfLimit$1(coll, limit, iteratee, callback) {476return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);477}478479var eachOfLimit$2 = awaitify(eachOfLimit$1, 4);480481// eachOf implementation optimized for array-likes482function eachOfArrayLike(coll, iteratee, callback) {483callback = once(callback);484var index = 0,485completed = 0,486{length} = coll,487canceled = false;488if (length === 0) {489callback(null);490}491492function iteratorCallback(err, value) {493if (err === false) {494canceled = true;495}496if (canceled === true) return497if (err) {498callback(err);499} else if ((++completed === length) || value === breakLoop) {500callback(null);501}502}503504for (; index < length; index++) {505iteratee(coll[index], index, onlyOnce(iteratorCallback));506}507}508509// a generic version of eachOf which can handle array, object, and iterator cases.510function eachOfGeneric (coll, iteratee, callback) {511return eachOfLimit$2(coll, Infinity, iteratee, callback);512}513514/**515* Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument516* to the iteratee.517*518* @name eachOf519* @static520* @memberOf module:Collections521* @method522* @alias forEachOf523* @category Collection524* @see [async.each]{@link module:Collections.each}525* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.526* @param {AsyncFunction} iteratee - A function to apply to each527* item in `coll`.528* The `key` is the item's key, or index in the case of an array.529* Invoked with (item, key, callback).530* @param {Function} [callback] - A callback which is called when all531* `iteratee` functions have finished, or an error occurs. Invoked with (err).532* @returns {Promise} a promise, if a callback is omitted533* @example534*535* // dev.json is a file containing a valid json object config for dev environment536* // dev.json is a file containing a valid json object config for test environment537* // prod.json is a file containing a valid json object config for prod environment538* // invalid.json is a file with a malformed json object539*540* let configs = {}; //global variable541* let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};542* let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};543*544* // asynchronous function that reads a json file and parses the contents as json object545* function parseFile(file, key, callback) {546* fs.readFile(file, "utf8", function(err, data) {547* if (err) return calback(err);548* try {549* configs[key] = JSON.parse(data);550* } catch (e) {551* return callback(e);552* }553* callback();554* });555* }556*557* // Using callbacks558* async.forEachOf(validConfigFileMap, parseFile, function (err) {559* if (err) {560* console.error(err);561* } else {562* console.log(configs);563* // configs is now a map of JSON data, e.g.564* // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}565* }566* });567*568* //Error handing569* async.forEachOf(invalidConfigFileMap, parseFile, function (err) {570* if (err) {571* console.error(err);572* // JSON parse error exception573* } else {574* console.log(configs);575* }576* });577*578* // Using Promises579* async.forEachOf(validConfigFileMap, parseFile)580* .then( () => {581* console.log(configs);582* // configs is now a map of JSON data, e.g.583* // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}584* }).catch( err => {585* console.error(err);586* });587*588* //Error handing589* async.forEachOf(invalidConfigFileMap, parseFile)590* .then( () => {591* console.log(configs);592* }).catch( err => {593* console.error(err);594* // JSON parse error exception595* });596*597* // Using async/await598* async () => {599* try {600* let result = await async.forEachOf(validConfigFileMap, parseFile);601* console.log(configs);602* // configs is now a map of JSON data, e.g.603* // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}604* }605* catch (err) {606* console.log(err);607* }608* }609*610* //Error handing611* async () => {612* try {613* let result = await async.forEachOf(invalidConfigFileMap, parseFile);614* console.log(configs);615* }616* catch (err) {617* console.log(err);618* // JSON parse error exception619* }620* }621*622*/623function eachOf(coll, iteratee, callback) {624var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;625return eachOfImplementation(coll, wrapAsync(iteratee), callback);626}627628var eachOf$1 = awaitify(eachOf, 3);629630/**631* Produces a new collection of values by mapping each value in `coll` through632* the `iteratee` function. The `iteratee` is called with an item from `coll`633* and a callback for when it has finished processing. Each of these callbacks634* takes 2 arguments: an `error`, and the transformed item from `coll`. If635* `iteratee` passes an error to its callback, the main `callback` (for the636* `map` function) is immediately called with the error.637*638* Note, that since this function applies the `iteratee` to each item in639* parallel, there is no guarantee that the `iteratee` functions will complete640* in order. However, the results array will be in the same order as the641* original `coll`.642*643* If `map` is passed an Object, the results will be an Array. The results644* will roughly be in the order of the original Objects' keys (but this can645* vary across JavaScript engines).646*647* @name map648* @static649* @memberOf module:Collections650* @method651* @category Collection652* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.653* @param {AsyncFunction} iteratee - An async function to apply to each item in654* `coll`.655* The iteratee should complete with the transformed item.656* Invoked with (item, callback).657* @param {Function} [callback] - A callback which is called when all `iteratee`658* functions have finished, or an error occurs. Results is an Array of the659* transformed items from the `coll`. Invoked with (err, results).660* @returns {Promise} a promise, if no callback is passed661* @example662*663* // file1.txt is a file that is 1000 bytes in size664* // file2.txt is a file that is 2000 bytes in size665* // file3.txt is a file that is 3000 bytes in size666* // file4.txt does not exist667*668* const fileList = ['file1.txt','file2.txt','file3.txt'];669* const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];670*671* // asynchronous function that returns the file size in bytes672* function getFileSizeInBytes(file, callback) {673* fs.stat(file, function(err, stat) {674* if (err) {675* return callback(err);676* }677* callback(null, stat.size);678* });679* }680*681* // Using callbacks682* async.map(fileList, getFileSizeInBytes, function(err, results) {683* if (err) {684* console.log(err);685* } else {686* console.log(results);687* // results is now an array of the file size in bytes for each file, e.g.688* // [ 1000, 2000, 3000]689* }690* });691*692* // Error Handling693* async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {694* if (err) {695* console.log(err);696* // [ Error: ENOENT: no such file or directory ]697* } else {698* console.log(results);699* }700* });701*702* // Using Promises703* async.map(fileList, getFileSizeInBytes)704* .then( results => {705* console.log(results);706* // results is now an array of the file size in bytes for each file, e.g.707* // [ 1000, 2000, 3000]708* }).catch( err => {709* console.log(err);710* });711*712* // Error Handling713* async.map(withMissingFileList, getFileSizeInBytes)714* .then( results => {715* console.log(results);716* }).catch( err => {717* console.log(err);718* // [ Error: ENOENT: no such file or directory ]719* });720*721* // Using async/await722* async () => {723* try {724* let results = await async.map(fileList, getFileSizeInBytes);725* console.log(results);726* // results is now an array of the file size in bytes for each file, e.g.727* // [ 1000, 2000, 3000]728* }729* catch (err) {730* console.log(err);731* }732* }733*734* // Error Handling735* async () => {736* try {737* let results = await async.map(withMissingFileList, getFileSizeInBytes);738* console.log(results);739* }740* catch (err) {741* console.log(err);742* // [ Error: ENOENT: no such file or directory ]743* }744* }745*746*/747function map (coll, iteratee, callback) {748return _asyncMap(eachOf$1, coll, iteratee, callback)749}750var map$1 = awaitify(map, 3);751752/**753* Applies the provided arguments to each function in the array, calling754* `callback` after all functions have completed. If you only provide the first755* argument, `fns`, then it will return a function which lets you pass in the756* arguments as if it were a single function call. If more arguments are757* provided, `callback` is required while `args` is still optional. The results758* for each of the applied async functions are passed to the final callback759* as an array.760*761* @name applyEach762* @static763* @memberOf module:ControlFlow764* @method765* @category Control Flow766* @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s767* to all call with the same arguments768* @param {...*} [args] - any number of separate arguments to pass to the769* function.770* @param {Function} [callback] - the final argument should be the callback,771* called when all functions have completed processing.772* @returns {AsyncFunction} - Returns a function that takes no args other than773* an optional callback, that is the result of applying the `args` to each774* of the functions.775* @example776*777* const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket')778*779* appliedFn((err, results) => {780* // results[0] is the results for `enableSearch`781* // results[1] is the results for `updateSchema`782* });783*784* // partial application example:785* async.each(786* buckets,787* async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(),788* callback789* );790*/791var applyEach$1 = applyEach(map$1);792793/**794* The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.795*796* @name eachOfSeries797* @static798* @memberOf module:Collections799* @method800* @see [async.eachOf]{@link module:Collections.eachOf}801* @alias forEachOfSeries802* @category Collection803* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.804* @param {AsyncFunction} iteratee - An async function to apply to each item in805* `coll`.806* Invoked with (item, key, callback).807* @param {Function} [callback] - A callback which is called when all `iteratee`808* functions have finished, or an error occurs. Invoked with (err).809* @returns {Promise} a promise, if a callback is omitted810*/811function eachOfSeries(coll, iteratee, callback) {812return eachOfLimit$2(coll, 1, iteratee, callback)813}814var eachOfSeries$1 = awaitify(eachOfSeries, 3);815816/**817* The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.818*819* @name mapSeries820* @static821* @memberOf module:Collections822* @method823* @see [async.map]{@link module:Collections.map}824* @category Collection825* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.826* @param {AsyncFunction} iteratee - An async function to apply to each item in827* `coll`.828* The iteratee should complete with the transformed item.829* Invoked with (item, callback).830* @param {Function} [callback] - A callback which is called when all `iteratee`831* functions have finished, or an error occurs. Results is an array of the832* transformed items from the `coll`. Invoked with (err, results).833* @returns {Promise} a promise, if no callback is passed834*/835function mapSeries (coll, iteratee, callback) {836return _asyncMap(eachOfSeries$1, coll, iteratee, callback)837}838var mapSeries$1 = awaitify(mapSeries, 3);839840/**841* The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.842*843* @name applyEachSeries844* @static845* @memberOf module:ControlFlow846* @method847* @see [async.applyEach]{@link module:ControlFlow.applyEach}848* @category Control Flow849* @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all850* call with the same arguments851* @param {...*} [args] - any number of separate arguments to pass to the852* function.853* @param {Function} [callback] - the final argument should be the callback,854* called when all functions have completed processing.855* @returns {AsyncFunction} - A function, that when called, is the result of856* appling the `args` to the list of functions. It takes no args, other than857* a callback.858*/859var applyEachSeries = applyEach(mapSeries$1);860861const PROMISE_SYMBOL = Symbol('promiseCallback');862863function promiseCallback () {864let resolve, reject;865function callback (err, ...args) {866if (err) return reject(err)867resolve(args.length > 1 ? args : args[0]);868}869870callback[PROMISE_SYMBOL] = new Promise((res, rej) => {871resolve = res,872reject = rej;873});874875return callback876}877878/**879* Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on880* their requirements. Each function can optionally depend on other functions881* being completed first, and each function is run as soon as its requirements882* are satisfied.883*884* If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence885* will stop. Further tasks will not execute (so any other functions depending886* on it will not run), and the main `callback` is immediately called with the887* error.888*889* {@link AsyncFunction}s also receive an object containing the results of functions which890* have completed so far as the first argument, if they have dependencies. If a891* task function has no dependencies, it will only be passed a callback.892*893* @name auto894* @static895* @memberOf module:ControlFlow896* @method897* @category Control Flow898* @param {Object} tasks - An object. Each of its properties is either a899* function or an array of requirements, with the {@link AsyncFunction} itself the last item900* in the array. The object's key of a property serves as the name of the task901* defined by that property, i.e. can be used when specifying requirements for902* other tasks. The function receives one or two arguments:903* * a `results` object, containing the results of the previously executed904* functions, only passed if the task has any dependencies,905* * a `callback(err, result)` function, which must be called when finished,906* passing an `error` (which can be `null`) and the result of the function's907* execution.908* @param {number} [concurrency=Infinity] - An optional `integer` for909* determining the maximum number of tasks that can be run in parallel. By910* default, as many as possible.911* @param {Function} [callback] - An optional callback which is called when all912* the tasks have been completed. It receives the `err` argument if any `tasks`913* pass an error to their callback. Results are always returned; however, if an914* error occurs, no further `tasks` will be performed, and the results object915* will only contain partial results. Invoked with (err, results).916* @returns {Promise} a promise, if a callback is not passed917* @example918*919* //Using Callbacks920* async.auto({921* get_data: function(callback) {922* // async code to get some data923* callback(null, 'data', 'converted to array');924* },925* make_folder: function(callback) {926* // async code to create a directory to store a file in927* // this is run at the same time as getting the data928* callback(null, 'folder');929* },930* write_file: ['get_data', 'make_folder', function(results, callback) {931* // once there is some data and the directory exists,932* // write the data to a file in the directory933* callback(null, 'filename');934* }],935* email_link: ['write_file', function(results, callback) {936* // once the file is written let's email a link to it...937* callback(null, {'file':results.write_file, 'email':'[email protected]'});938* }]939* }, function(err, results) {940* if (err) {941* console.log('err = ', err);942* }943* console.log('results = ', results);944* // results = {945* // get_data: ['data', 'converted to array']946* // make_folder; 'folder',947* // write_file: 'filename'948* // email_link: { file: 'filename', email: '[email protected]' }949* // }950* });951*952* //Using Promises953* async.auto({954* get_data: function(callback) {955* console.log('in get_data');956* // async code to get some data957* callback(null, 'data', 'converted to array');958* },959* make_folder: function(callback) {960* console.log('in make_folder');961* // async code to create a directory to store a file in962* // this is run at the same time as getting the data963* callback(null, 'folder');964* },965* write_file: ['get_data', 'make_folder', function(results, callback) {966* // once there is some data and the directory exists,967* // write the data to a file in the directory968* callback(null, 'filename');969* }],970* email_link: ['write_file', function(results, callback) {971* // once the file is written let's email a link to it...972* callback(null, {'file':results.write_file, 'email':'[email protected]'});973* }]974* }).then(results => {975* console.log('results = ', results);976* // results = {977* // get_data: ['data', 'converted to array']978* // make_folder; 'folder',979* // write_file: 'filename'980* // email_link: { file: 'filename', email: '[email protected]' }981* // }982* }).catch(err => {983* console.log('err = ', err);984* });985*986* //Using async/await987* async () => {988* try {989* let results = await async.auto({990* get_data: function(callback) {991* // async code to get some data992* callback(null, 'data', 'converted to array');993* },994* make_folder: function(callback) {995* // async code to create a directory to store a file in996* // this is run at the same time as getting the data997* callback(null, 'folder');998* },999* write_file: ['get_data', 'make_folder', function(results, callback) {1000* // once there is some data and the directory exists,1001* // write the data to a file in the directory1002* callback(null, 'filename');1003* }],1004* email_link: ['write_file', function(results, callback) {1005* // once the file is written let's email a link to it...1006* callback(null, {'file':results.write_file, 'email':'[email protected]'});1007* }]1008* });1009* console.log('results = ', results);1010* // results = {1011* // get_data: ['data', 'converted to array']1012* // make_folder; 'folder',1013* // write_file: 'filename'1014* // email_link: { file: 'filename', email: '[email protected]' }1015* // }1016* }1017* catch (err) {1018* console.log(err);1019* }1020* }1021*1022*/1023function auto(tasks, concurrency, callback) {1024if (typeof concurrency !== 'number') {1025// concurrency is optional, shift the args.1026callback = concurrency;1027concurrency = null;1028}1029callback = once(callback || promiseCallback());1030var numTasks = Object.keys(tasks).length;1031if (!numTasks) {1032return callback(null);1033}1034if (!concurrency) {1035concurrency = numTasks;1036}10371038var results = {};1039var runningTasks = 0;1040var canceled = false;1041var hasError = false;10421043var listeners = Object.create(null);10441045var readyTasks = [];10461047// for cycle detection:1048var readyToCheck = []; // tasks that have been identified as reachable1049// without the possibility of returning to an ancestor task1050var uncheckedDependencies = {};10511052Object.keys(tasks).forEach(key => {1053var task = tasks[key];1054if (!Array.isArray(task)) {1055// no dependencies1056enqueueTask(key, [task]);1057readyToCheck.push(key);1058return;1059}10601061var dependencies = task.slice(0, task.length - 1);1062var remainingDependencies = dependencies.length;1063if (remainingDependencies === 0) {1064enqueueTask(key, task);1065readyToCheck.push(key);1066return;1067}1068uncheckedDependencies[key] = remainingDependencies;10691070dependencies.forEach(dependencyName => {1071if (!tasks[dependencyName]) {1072throw new Error('async.auto task `' + key +1073'` has a non-existent dependency `' +1074dependencyName + '` in ' +1075dependencies.join(', '));1076}1077addListener(dependencyName, () => {1078remainingDependencies--;1079if (remainingDependencies === 0) {1080enqueueTask(key, task);1081}1082});1083});1084});10851086checkForDeadlocks();1087processQueue();10881089function enqueueTask(key, task) {1090readyTasks.push(() => runTask(key, task));1091}10921093function processQueue() {1094if (canceled) return1095if (readyTasks.length === 0 && runningTasks === 0) {1096return callback(null, results);1097}1098while(readyTasks.length && runningTasks < concurrency) {1099var run = readyTasks.shift();1100run();1101}11021103}11041105function addListener(taskName, fn) {1106var taskListeners = listeners[taskName];1107if (!taskListeners) {1108taskListeners = listeners[taskName] = [];1109}11101111taskListeners.push(fn);1112}11131114function taskComplete(taskName) {1115var taskListeners = listeners[taskName] || [];1116taskListeners.forEach(fn => fn());1117processQueue();1118}111911201121function runTask(key, task) {1122if (hasError) return;11231124var taskCallback = onlyOnce((err, ...result) => {1125runningTasks--;1126if (err === false) {1127canceled = true;1128return1129}1130if (result.length < 2) {1131[result] = result;1132}1133if (err) {1134var safeResults = {};1135Object.keys(results).forEach(rkey => {1136safeResults[rkey] = results[rkey];1137});1138safeResults[key] = result;1139hasError = true;1140listeners = Object.create(null);1141if (canceled) return1142callback(err, safeResults);1143} else {1144results[key] = result;1145taskComplete(key);1146}1147});11481149runningTasks++;1150var taskFn = wrapAsync(task[task.length - 1]);1151if (task.length > 1) {1152taskFn(results, taskCallback);1153} else {1154taskFn(taskCallback);1155}1156}11571158function checkForDeadlocks() {1159// Kahn's algorithm1160// https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm1161// http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html1162var currentTask;1163var counter = 0;1164while (readyToCheck.length) {1165currentTask = readyToCheck.pop();1166counter++;1167getDependents(currentTask).forEach(dependent => {1168if (--uncheckedDependencies[dependent] === 0) {1169readyToCheck.push(dependent);1170}1171});1172}11731174if (counter !== numTasks) {1175throw new Error(1176'async.auto cannot execute tasks due to a recursive dependency'1177);1178}1179}11801181function getDependents(taskName) {1182var result = [];1183Object.keys(tasks).forEach(key => {1184const task = tasks[key];1185if (Array.isArray(task) && task.indexOf(taskName) >= 0) {1186result.push(key);1187}1188});1189return result;1190}11911192return callback[PROMISE_SYMBOL]1193}11941195var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/;1196var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/;1197var FN_ARG_SPLIT = /,/;1198var FN_ARG = /(=.+)?(\s*)$/;11991200function stripComments(string) {1201let stripped = '';1202let index = 0;1203let endBlockComment = string.indexOf('*/');1204while (index < string.length) {1205if (string[index] === '/' && string[index+1] === '/') {1206// inline comment1207let endIndex = string.indexOf('\n', index);1208index = (endIndex === -1) ? string.length : endIndex;1209} else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) {1210// block comment1211let endIndex = string.indexOf('*/', index);1212if (endIndex !== -1) {1213index = endIndex + 2;1214endBlockComment = string.indexOf('*/', index);1215} else {1216stripped += string[index];1217index++;1218}1219} else {1220stripped += string[index];1221index++;1222}1223}1224return stripped;1225}12261227function parseParams(func) {1228const src = stripComments(func.toString());1229let match = src.match(FN_ARGS);1230if (!match) {1231match = src.match(ARROW_FN_ARGS);1232}1233if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src)1234let [, args] = match;1235return args1236.replace(/\s/g, '')1237.split(FN_ARG_SPLIT)1238.map((arg) => arg.replace(FN_ARG, '').trim());1239}12401241/**1242* A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent1243* tasks are specified as parameters to the function, after the usual callback1244* parameter, with the parameter names matching the names of the tasks it1245* depends on. This can provide even more readable task graphs which can be1246* easier to maintain.1247*1248* If a final callback is specified, the task results are similarly injected,1249* specified as named parameters after the initial error parameter.1250*1251* The autoInject function is purely syntactic sugar and its semantics are1252* otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.1253*1254* @name autoInject1255* @static1256* @memberOf module:ControlFlow1257* @method1258* @see [async.auto]{@link module:ControlFlow.auto}1259* @category Control Flow1260* @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of1261* the form 'func([dependencies...], callback). The object's key of a property1262* serves as the name of the task defined by that property, i.e. can be used1263* when specifying requirements for other tasks.1264* * The `callback` parameter is a `callback(err, result)` which must be called1265* when finished, passing an `error` (which can be `null`) and the result of1266* the function's execution. The remaining parameters name other tasks on1267* which the task is dependent, and the results from those tasks are the1268* arguments of those parameters.1269* @param {Function} [callback] - An optional callback which is called when all1270* the tasks have been completed. It receives the `err` argument if any `tasks`1271* pass an error to their callback, and a `results` object with any completed1272* task results, similar to `auto`.1273* @returns {Promise} a promise, if no callback is passed1274* @example1275*1276* // The example from `auto` can be rewritten as follows:1277* async.autoInject({1278* get_data: function(callback) {1279* // async code to get some data1280* callback(null, 'data', 'converted to array');1281* },1282* make_folder: function(callback) {1283* // async code to create a directory to store a file in1284* // this is run at the same time as getting the data1285* callback(null, 'folder');1286* },1287* write_file: function(get_data, make_folder, callback) {1288* // once there is some data and the directory exists,1289* // write the data to a file in the directory1290* callback(null, 'filename');1291* },1292* email_link: function(write_file, callback) {1293* // once the file is written let's email a link to it...1294* // write_file contains the filename returned by write_file.1295* callback(null, {'file':write_file, 'email':'[email protected]'});1296* }1297* }, function(err, results) {1298* console.log('err = ', err);1299* console.log('email_link = ', results.email_link);1300* });1301*1302* // If you are using a JS minifier that mangles parameter names, `autoInject`1303* // will not work with plain functions, since the parameter names will be1304* // collapsed to a single letter identifier. To work around this, you can1305* // explicitly specify the names of the parameters your task function needs1306* // in an array, similar to Angular.js dependency injection.1307*1308* // This still has an advantage over plain `auto`, since the results a task1309* // depends on are still spread into arguments.1310* async.autoInject({1311* //...1312* write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {1313* callback(null, 'filename');1314* }],1315* email_link: ['write_file', function(write_file, callback) {1316* callback(null, {'file':write_file, 'email':'[email protected]'});1317* }]1318* //...1319* }, function(err, results) {1320* console.log('err = ', err);1321* console.log('email_link = ', results.email_link);1322* });1323*/1324function autoInject(tasks, callback) {1325var newTasks = {};13261327Object.keys(tasks).forEach(key => {1328var taskFn = tasks[key];1329var params;1330var fnIsAsync = isAsync(taskFn);1331var hasNoDeps =1332(!fnIsAsync && taskFn.length === 1) ||1333(fnIsAsync && taskFn.length === 0);13341335if (Array.isArray(taskFn)) {1336params = [...taskFn];1337taskFn = params.pop();13381339newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);1340} else if (hasNoDeps) {1341// no dependencies, use the function as-is1342newTasks[key] = taskFn;1343} else {1344params = parseParams(taskFn);1345if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) {1346throw new Error("autoInject task functions require explicit parameters.");1347}13481349// remove callback param1350if (!fnIsAsync) params.pop();13511352newTasks[key] = params.concat(newTask);1353}13541355function newTask(results, taskCb) {1356var newArgs = params.map(name => results[name]);1357newArgs.push(taskCb);1358wrapAsync(taskFn)(...newArgs);1359}1360});13611362return auto(newTasks, callback);1363}13641365// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation1366// used for queues. This implementation assumes that the node provided by the user can be modified1367// to adjust the next and last properties. We implement only the minimal functionality1368// for queue support.1369class DLL {1370constructor() {1371this.head = this.tail = null;1372this.length = 0;1373}13741375removeLink(node) {1376if (node.prev) node.prev.next = node.next;1377else this.head = node.next;1378if (node.next) node.next.prev = node.prev;1379else this.tail = node.prev;13801381node.prev = node.next = null;1382this.length -= 1;1383return node;1384}13851386empty () {1387while(this.head) this.shift();1388return this;1389}13901391insertAfter(node, newNode) {1392newNode.prev = node;1393newNode.next = node.next;1394if (node.next) node.next.prev = newNode;1395else this.tail = newNode;1396node.next = newNode;1397this.length += 1;1398}13991400insertBefore(node, newNode) {1401newNode.prev = node.prev;1402newNode.next = node;1403if (node.prev) node.prev.next = newNode;1404else this.head = newNode;1405node.prev = newNode;1406this.length += 1;1407}14081409unshift(node) {1410if (this.head) this.insertBefore(this.head, node);1411else setInitial(this, node);1412}14131414push(node) {1415if (this.tail) this.insertAfter(this.tail, node);1416else setInitial(this, node);1417}14181419shift() {1420return this.head && this.removeLink(this.head);1421}14221423pop() {1424return this.tail && this.removeLink(this.tail);1425}14261427toArray() {1428return [...this]1429}14301431*[Symbol.iterator] () {1432var cur = this.head;1433while (cur) {1434yield cur.data;1435cur = cur.next;1436}1437}14381439remove (testFn) {1440var curr = this.head;1441while(curr) {1442var {next} = curr;1443if (testFn(curr)) {1444this.removeLink(curr);1445}1446curr = next;1447}1448return this;1449}1450}14511452function setInitial(dll, node) {1453dll.length = 1;1454dll.head = dll.tail = node;1455}14561457function queue(worker, concurrency, payload) {1458if (concurrency == null) {1459concurrency = 1;1460}1461else if(concurrency === 0) {1462throw new RangeError('Concurrency must not be zero');1463}14641465var _worker = wrapAsync(worker);1466var numRunning = 0;1467var workersList = [];1468const events = {1469error: [],1470drain: [],1471saturated: [],1472unsaturated: [],1473empty: []1474};14751476function on (event, handler) {1477events[event].push(handler);1478}14791480function once (event, handler) {1481const handleAndRemove = (...args) => {1482off(event, handleAndRemove);1483handler(...args);1484};1485events[event].push(handleAndRemove);1486}14871488function off (event, handler) {1489if (!event) return Object.keys(events).forEach(ev => events[ev] = [])1490if (!handler) return events[event] = []1491events[event] = events[event].filter(ev => ev !== handler);1492}14931494function trigger (event, ...args) {1495events[event].forEach(handler => handler(...args));1496}14971498var processingScheduled = false;1499function _insert(data, insertAtFront, rejectOnError, callback) {1500if (callback != null && typeof callback !== 'function') {1501throw new Error('task callback must be a function');1502}1503q.started = true;15041505var res, rej;1506function promiseCallback (err, ...args) {1507// we don't care about the error, let the global error handler1508// deal with it1509if (err) return rejectOnError ? rej(err) : res()1510if (args.length <= 1) return res(args[0])1511res(args);1512}15131514var item = q._createTaskItem(1515data,1516rejectOnError ? promiseCallback :1517(callback || promiseCallback)1518);15191520if (insertAtFront) {1521q._tasks.unshift(item);1522} else {1523q._tasks.push(item);1524}15251526if (!processingScheduled) {1527processingScheduled = true;1528setImmediate$1(() => {1529processingScheduled = false;1530q.process();1531});1532}15331534if (rejectOnError || !callback) {1535return new Promise((resolve, reject) => {1536res = resolve;1537rej = reject;1538})1539}1540}15411542function _createCB(tasks) {1543return function (err, ...args) {1544numRunning -= 1;15451546for (var i = 0, l = tasks.length; i < l; i++) {1547var task = tasks[i];15481549var index = workersList.indexOf(task);1550if (index === 0) {1551workersList.shift();1552} else if (index > 0) {1553workersList.splice(index, 1);1554}15551556task.callback(err, ...args);15571558if (err != null) {1559trigger('error', err, task.data);1560}1561}15621563if (numRunning <= (q.concurrency - q.buffer) ) {1564trigger('unsaturated');1565}15661567if (q.idle()) {1568trigger('drain');1569}1570q.process();1571};1572}15731574function _maybeDrain(data) {1575if (data.length === 0 && q.idle()) {1576// call drain immediately if there are no tasks1577setImmediate$1(() => trigger('drain'));1578return true1579}1580return false1581}15821583const eventMethod = (name) => (handler) => {1584if (!handler) {1585return new Promise((resolve, reject) => {1586once(name, (err, data) => {1587if (err) return reject(err)1588resolve(data);1589});1590})1591}1592off(name);1593on(name, handler);15941595};15961597var isProcessing = false;1598var q = {1599_tasks: new DLL(),1600_createTaskItem (data, callback) {1601return {1602data,1603callback1604};1605},1606*[Symbol.iterator] () {1607yield* q._tasks[Symbol.iterator]();1608},1609concurrency,1610payload,1611buffer: concurrency / 4,1612started: false,1613paused: false,1614push (data, callback) {1615if (Array.isArray(data)) {1616if (_maybeDrain(data)) return1617return data.map(datum => _insert(datum, false, false, callback))1618}1619return _insert(data, false, false, callback);1620},1621pushAsync (data, callback) {1622if (Array.isArray(data)) {1623if (_maybeDrain(data)) return1624return data.map(datum => _insert(datum, false, true, callback))1625}1626return _insert(data, false, true, callback);1627},1628kill () {1629off();1630q._tasks.empty();1631},1632unshift (data, callback) {1633if (Array.isArray(data)) {1634if (_maybeDrain(data)) return1635return data.map(datum => _insert(datum, true, false, callback))1636}1637return _insert(data, true, false, callback);1638},1639unshiftAsync (data, callback) {1640if (Array.isArray(data)) {1641if (_maybeDrain(data)) return1642return data.map(datum => _insert(datum, true, true, callback))1643}1644return _insert(data, true, true, callback);1645},1646remove (testFn) {1647q._tasks.remove(testFn);1648},1649process () {1650// Avoid trying to start too many processing operations. This can occur1651// when callbacks resolve synchronously (#1267).1652if (isProcessing) {1653return;1654}1655isProcessing = true;1656while(!q.paused && numRunning < q.concurrency && q._tasks.length){1657var tasks = [], data = [];1658var l = q._tasks.length;1659if (q.payload) l = Math.min(l, q.payload);1660for (var i = 0; i < l; i++) {1661var node = q._tasks.shift();1662tasks.push(node);1663workersList.push(node);1664data.push(node.data);1665}16661667numRunning += 1;16681669if (q._tasks.length === 0) {1670trigger('empty');1671}16721673if (numRunning === q.concurrency) {1674trigger('saturated');1675}16761677var cb = onlyOnce(_createCB(tasks));1678_worker(data, cb);1679}1680isProcessing = false;1681},1682length () {1683return q._tasks.length;1684},1685running () {1686return numRunning;1687},1688workersList () {1689return workersList;1690},1691idle() {1692return q._tasks.length + numRunning === 0;1693},1694pause () {1695q.paused = true;1696},1697resume () {1698if (q.paused === false) { return; }1699q.paused = false;1700setImmediate$1(q.process);1701}1702};1703// define these as fixed properties, so people get useful errors when updating1704Object.defineProperties(q, {1705saturated: {1706writable: false,1707value: eventMethod('saturated')1708},1709unsaturated: {1710writable: false,1711value: eventMethod('unsaturated')1712},1713empty: {1714writable: false,1715value: eventMethod('empty')1716},1717drain: {1718writable: false,1719value: eventMethod('drain')1720},1721error: {1722writable: false,1723value: eventMethod('error')1724},1725});1726return q;1727}17281729/**1730* Creates a `cargo` object with the specified payload. Tasks added to the1731* cargo will be processed altogether (up to the `payload` limit). If the1732* `worker` is in progress, the task is queued until it becomes available. Once1733* the `worker` has completed some tasks, each callback of those tasks is1734* called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)1735* for how `cargo` and `queue` work.1736*1737* While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers1738* at a time, cargo passes an array of tasks to a single worker, repeating1739* when the worker is finished.1740*1741* @name cargo1742* @static1743* @memberOf module:ControlFlow1744* @method1745* @see [async.queue]{@link module:ControlFlow.queue}1746* @category Control Flow1747* @param {AsyncFunction} worker - An asynchronous function for processing an array1748* of queued tasks. Invoked with `(tasks, callback)`.1749* @param {number} [payload=Infinity] - An optional `integer` for determining1750* how many tasks should be processed per round; if omitted, the default is1751* unlimited.1752* @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can1753* attached as certain properties to listen for specific events during the1754* lifecycle of the cargo and inner queue.1755* @example1756*1757* // create a cargo object with payload 21758* var cargo = async.cargo(function(tasks, callback) {1759* for (var i=0; i<tasks.length; i++) {1760* console.log('hello ' + tasks[i].name);1761* }1762* callback();1763* }, 2);1764*1765* // add some items1766* cargo.push({name: 'foo'}, function(err) {1767* console.log('finished processing foo');1768* });1769* cargo.push({name: 'bar'}, function(err) {1770* console.log('finished processing bar');1771* });1772* await cargo.push({name: 'baz'});1773* console.log('finished processing baz');1774*/1775function cargo(worker, payload) {1776return queue(worker, 1, payload);1777}17781779/**1780* Creates a `cargoQueue` object with the specified payload. Tasks added to the1781* cargoQueue will be processed together (up to the `payload` limit) in `concurrency` parallel workers.1782* If the all `workers` are in progress, the task is queued until one becomes available. Once1783* a `worker` has completed some tasks, each callback of those tasks is1784* called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)1785* for how `cargo` and `queue` work.1786*1787* While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers1788* at a time, and [`cargo`]{@link module:ControlFlow.cargo} passes an array of tasks to a single worker,1789* the cargoQueue passes an array of tasks to multiple parallel workers.1790*1791* @name cargoQueue1792* @static1793* @memberOf module:ControlFlow1794* @method1795* @see [async.queue]{@link module:ControlFlow.queue}1796* @see [async.cargo]{@link module:ControlFLow.cargo}1797* @category Control Flow1798* @param {AsyncFunction} worker - An asynchronous function for processing an array1799* of queued tasks. Invoked with `(tasks, callback)`.1800* @param {number} [concurrency=1] - An `integer` for determining how many1801* `worker` functions should be run in parallel. If omitted, the concurrency1802* defaults to `1`. If the concurrency is `0`, an error is thrown.1803* @param {number} [payload=Infinity] - An optional `integer` for determining1804* how many tasks should be processed per round; if omitted, the default is1805* unlimited.1806* @returns {module:ControlFlow.QueueObject} A cargoQueue object to manage the tasks. Callbacks can1807* attached as certain properties to listen for specific events during the1808* lifecycle of the cargoQueue and inner queue.1809* @example1810*1811* // create a cargoQueue object with payload 2 and concurrency 21812* var cargoQueue = async.cargoQueue(function(tasks, callback) {1813* for (var i=0; i<tasks.length; i++) {1814* console.log('hello ' + tasks[i].name);1815* }1816* callback();1817* }, 2, 2);1818*1819* // add some items1820* cargoQueue.push({name: 'foo'}, function(err) {1821* console.log('finished processing foo');1822* });1823* cargoQueue.push({name: 'bar'}, function(err) {1824* console.log('finished processing bar');1825* });1826* cargoQueue.push({name: 'baz'}, function(err) {1827* console.log('finished processing baz');1828* });1829* cargoQueue.push({name: 'boo'}, function(err) {1830* console.log('finished processing boo');1831* });1832*/1833function cargo$1(worker, concurrency, payload) {1834return queue(worker, concurrency, payload);1835}18361837/**1838* Reduces `coll` into a single value using an async `iteratee` to return each1839* successive step. `memo` is the initial state of the reduction. This function1840* only operates in series.1841*1842* For performance reasons, it may make sense to split a call to this function1843* into a parallel map, and then use the normal `Array.prototype.reduce` on the1844* results. This function is for situations where each step in the reduction1845* needs to be async; if you can get the data before reducing it, then it's1846* probably a good idea to do so.1847*1848* @name reduce1849* @static1850* @memberOf module:Collections1851* @method1852* @alias inject1853* @alias foldl1854* @category Collection1855* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.1856* @param {*} memo - The initial state of the reduction.1857* @param {AsyncFunction} iteratee - A function applied to each item in the1858* array to produce the next step in the reduction.1859* The `iteratee` should complete with the next state of the reduction.1860* If the iteratee completes with an error, the reduction is stopped and the1861* main `callback` is immediately called with the error.1862* Invoked with (memo, item, callback).1863* @param {Function} [callback] - A callback which is called after all the1864* `iteratee` functions have finished. Result is the reduced value. Invoked with1865* (err, result).1866* @returns {Promise} a promise, if no callback is passed1867* @example1868*1869* // file1.txt is a file that is 1000 bytes in size1870* // file2.txt is a file that is 2000 bytes in size1871* // file3.txt is a file that is 3000 bytes in size1872* // file4.txt does not exist1873*1874* const fileList = ['file1.txt','file2.txt','file3.txt'];1875* const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt'];1876*1877* // asynchronous function that computes the file size in bytes1878* // file size is added to the memoized value, then returned1879* function getFileSizeInBytes(memo, file, callback) {1880* fs.stat(file, function(err, stat) {1881* if (err) {1882* return callback(err);1883* }1884* callback(null, memo + stat.size);1885* });1886* }1887*1888* // Using callbacks1889* async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) {1890* if (err) {1891* console.log(err);1892* } else {1893* console.log(result);1894* // 60001895* // which is the sum of the file sizes of the three files1896* }1897* });1898*1899* // Error Handling1900* async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) {1901* if (err) {1902* console.log(err);1903* // [ Error: ENOENT: no such file or directory ]1904* } else {1905* console.log(result);1906* }1907* });1908*1909* // Using Promises1910* async.reduce(fileList, 0, getFileSizeInBytes)1911* .then( result => {1912* console.log(result);1913* // 60001914* // which is the sum of the file sizes of the three files1915* }).catch( err => {1916* console.log(err);1917* });1918*1919* // Error Handling1920* async.reduce(withMissingFileList, 0, getFileSizeInBytes)1921* .then( result => {1922* console.log(result);1923* }).catch( err => {1924* console.log(err);1925* // [ Error: ENOENT: no such file or directory ]1926* });1927*1928* // Using async/await1929* async () => {1930* try {1931* let result = await async.reduce(fileList, 0, getFileSizeInBytes);1932* console.log(result);1933* // 60001934* // which is the sum of the file sizes of the three files1935* }1936* catch (err) {1937* console.log(err);1938* }1939* }1940*1941* // Error Handling1942* async () => {1943* try {1944* let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes);1945* console.log(result);1946* }1947* catch (err) {1948* console.log(err);1949* // [ Error: ENOENT: no such file or directory ]1950* }1951* }1952*1953*/1954function reduce(coll, memo, iteratee, callback) {1955callback = once(callback);1956var _iteratee = wrapAsync(iteratee);1957return eachOfSeries$1(coll, (x, i, iterCb) => {1958_iteratee(memo, x, (err, v) => {1959memo = v;1960iterCb(err);1961});1962}, err => callback(err, memo));1963}1964var reduce$1 = awaitify(reduce, 4);19651966/**1967* Version of the compose function that is more natural to read. Each function1968* consumes the return value of the previous function. It is the equivalent of1969* [compose]{@link module:ControlFlow.compose} with the arguments reversed.1970*1971* Each function is executed with the `this` binding of the composed function.1972*1973* @name seq1974* @static1975* @memberOf module:ControlFlow1976* @method1977* @see [async.compose]{@link module:ControlFlow.compose}1978* @category Control Flow1979* @param {...AsyncFunction} functions - the asynchronous functions to compose1980* @returns {Function} a function that composes the `functions` in order1981* @example1982*1983* // Requires lodash (or underscore), express3 and dresende's orm2.1984* // Part of an app, that fetches cats of the logged user.1985* // This example uses `seq` function to avoid overnesting and error1986* // handling clutter.1987* app.get('/cats', function(request, response) {1988* var User = request.models.User;1989* async.seq(1990* User.get.bind(User), // 'User.get' has signature (id, callback(err, data))1991* function(user, fn) {1992* user.getCats(fn); // 'getCats' has signature (callback(err, data))1993* }1994* )(req.session.user_id, function (err, cats) {1995* if (err) {1996* console.error(err);1997* response.json({ status: 'error', message: err.message });1998* } else {1999* response.json({ status: 'ok', message: 'Cats found', data: cats });2000* }2001* });2002* });2003*/2004function seq(...functions) {2005var _functions = functions.map(wrapAsync);2006return function (...args) {2007var that = this;20082009var cb = args[args.length - 1];2010if (typeof cb == 'function') {2011args.pop();2012} else {2013cb = promiseCallback();2014}20152016reduce$1(_functions, args, (newargs, fn, iterCb) => {2017fn.apply(that, newargs.concat((err, ...nextargs) => {2018iterCb(err, nextargs);2019}));2020},2021(err, results) => cb(err, ...results));20222023return cb[PROMISE_SYMBOL]2024};2025}20262027/**2028* Creates a function which is a composition of the passed asynchronous2029* functions. Each function consumes the return value of the function that2030* follows. Composing functions `f()`, `g()`, and `h()` would produce the result2031* of `f(g(h()))`, only this version uses callbacks to obtain the return values.2032*2033* If the last argument to the composed function is not a function, a promise2034* is returned when you call it.2035*2036* Each function is executed with the `this` binding of the composed function.2037*2038* @name compose2039* @static2040* @memberOf module:ControlFlow2041* @method2042* @category Control Flow2043* @param {...AsyncFunction} functions - the asynchronous functions to compose2044* @returns {Function} an asynchronous function that is the composed2045* asynchronous `functions`2046* @example2047*2048* function add1(n, callback) {2049* setTimeout(function () {2050* callback(null, n + 1);2051* }, 10);2052* }2053*2054* function mul3(n, callback) {2055* setTimeout(function () {2056* callback(null, n * 3);2057* }, 10);2058* }2059*2060* var add1mul3 = async.compose(mul3, add1);2061* add1mul3(4, function (err, result) {2062* // result now equals 152063* });2064*/2065function compose(...args) {2066return seq(...args.reverse());2067}20682069/**2070* The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.2071*2072* @name mapLimit2073* @static2074* @memberOf module:Collections2075* @method2076* @see [async.map]{@link module:Collections.map}2077* @category Collection2078* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2079* @param {number} limit - The maximum number of async operations at a time.2080* @param {AsyncFunction} iteratee - An async function to apply to each item in2081* `coll`.2082* The iteratee should complete with the transformed item.2083* Invoked with (item, callback).2084* @param {Function} [callback] - A callback which is called when all `iteratee`2085* functions have finished, or an error occurs. Results is an array of the2086* transformed items from the `coll`. Invoked with (err, results).2087* @returns {Promise} a promise, if no callback is passed2088*/2089function mapLimit (coll, limit, iteratee, callback) {2090return _asyncMap(eachOfLimit(limit), coll, iteratee, callback)2091}2092var mapLimit$1 = awaitify(mapLimit, 4);20932094/**2095* The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.2096*2097* @name concatLimit2098* @static2099* @memberOf module:Collections2100* @method2101* @see [async.concat]{@link module:Collections.concat}2102* @category Collection2103* @alias flatMapLimit2104* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2105* @param {number} limit - The maximum number of async operations at a time.2106* @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,2107* which should use an array as its result. Invoked with (item, callback).2108* @param {Function} [callback] - A callback which is called after all the2109* `iteratee` functions have finished, or an error occurs. Results is an array2110* containing the concatenated results of the `iteratee` function. Invoked with2111* (err, results).2112* @returns A Promise, if no callback is passed2113*/2114function concatLimit(coll, limit, iteratee, callback) {2115var _iteratee = wrapAsync(iteratee);2116return mapLimit$1(coll, limit, (val, iterCb) => {2117_iteratee(val, (err, ...args) => {2118if (err) return iterCb(err);2119return iterCb(err, args);2120});2121}, (err, mapResults) => {2122var result = [];2123for (var i = 0; i < mapResults.length; i++) {2124if (mapResults[i]) {2125result = result.concat(...mapResults[i]);2126}2127}21282129return callback(err, result);2130});2131}2132var concatLimit$1 = awaitify(concatLimit, 4);21332134/**2135* Applies `iteratee` to each item in `coll`, concatenating the results. Returns2136* the concatenated list. The `iteratee`s are called in parallel, and the2137* results are concatenated as they return. The results array will be returned in2138* the original order of `coll` passed to the `iteratee` function.2139*2140* @name concat2141* @static2142* @memberOf module:Collections2143* @method2144* @category Collection2145* @alias flatMap2146* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2147* @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,2148* which should use an array as its result. Invoked with (item, callback).2149* @param {Function} [callback] - A callback which is called after all the2150* `iteratee` functions have finished, or an error occurs. Results is an array2151* containing the concatenated results of the `iteratee` function. Invoked with2152* (err, results).2153* @returns A Promise, if no callback is passed2154* @example2155*2156* // dir1 is a directory that contains file1.txt, file2.txt2157* // dir2 is a directory that contains file3.txt, file4.txt2158* // dir3 is a directory that contains file5.txt2159* // dir4 does not exist2160*2161* let directoryList = ['dir1','dir2','dir3'];2162* let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4'];2163*2164* // Using callbacks2165* async.concat(directoryList, fs.readdir, function(err, results) {2166* if (err) {2167* console.log(err);2168* } else {2169* console.log(results);2170* // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]2171* }2172* });2173*2174* // Error Handling2175* async.concat(withMissingDirectoryList, fs.readdir, function(err, results) {2176* if (err) {2177* console.log(err);2178* // [ Error: ENOENT: no such file or directory ]2179* // since dir4 does not exist2180* } else {2181* console.log(results);2182* }2183* });2184*2185* // Using Promises2186* async.concat(directoryList, fs.readdir)2187* .then(results => {2188* console.log(results);2189* // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]2190* }).catch(err => {2191* console.log(err);2192* });2193*2194* // Error Handling2195* async.concat(withMissingDirectoryList, fs.readdir)2196* .then(results => {2197* console.log(results);2198* }).catch(err => {2199* console.log(err);2200* // [ Error: ENOENT: no such file or directory ]2201* // since dir4 does not exist2202* });2203*2204* // Using async/await2205* async () => {2206* try {2207* let results = await async.concat(directoryList, fs.readdir);2208* console.log(results);2209* // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]2210* } catch (err) {2211* console.log(err);2212* }2213* }2214*2215* // Error Handling2216* async () => {2217* try {2218* let results = await async.concat(withMissingDirectoryList, fs.readdir);2219* console.log(results);2220* } catch (err) {2221* console.log(err);2222* // [ Error: ENOENT: no such file or directory ]2223* // since dir4 does not exist2224* }2225* }2226*2227*/2228function concat(coll, iteratee, callback) {2229return concatLimit$1(coll, Infinity, iteratee, callback)2230}2231var concat$1 = awaitify(concat, 3);22322233/**2234* The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.2235*2236* @name concatSeries2237* @static2238* @memberOf module:Collections2239* @method2240* @see [async.concat]{@link module:Collections.concat}2241* @category Collection2242* @alias flatMapSeries2243* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2244* @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.2245* The iteratee should complete with an array an array of results.2246* Invoked with (item, callback).2247* @param {Function} [callback] - A callback which is called after all the2248* `iteratee` functions have finished, or an error occurs. Results is an array2249* containing the concatenated results of the `iteratee` function. Invoked with2250* (err, results).2251* @returns A Promise, if no callback is passed2252*/2253function concatSeries(coll, iteratee, callback) {2254return concatLimit$1(coll, 1, iteratee, callback)2255}2256var concatSeries$1 = awaitify(concatSeries, 3);22572258/**2259* Returns a function that when called, calls-back with the values provided.2260* Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to2261* [`auto`]{@link module:ControlFlow.auto}.2262*2263* @name constant2264* @static2265* @memberOf module:Utils2266* @method2267* @category Util2268* @param {...*} arguments... - Any number of arguments to automatically invoke2269* callback with.2270* @returns {AsyncFunction} Returns a function that when invoked, automatically2271* invokes the callback with the previous given arguments.2272* @example2273*2274* async.waterfall([2275* async.constant(42),2276* function (value, next) {2277* // value === 422278* },2279* //...2280* ], callback);2281*2282* async.waterfall([2283* async.constant(filename, "utf8"),2284* fs.readFile,2285* function (fileData, next) {2286* //...2287* }2288* //...2289* ], callback);2290*2291* async.auto({2292* hostname: async.constant("https://server.net/"),2293* port: findFreePort,2294* launchServer: ["hostname", "port", function (options, cb) {2295* startServer(options, cb);2296* }],2297* //...2298* }, callback);2299*/2300function constant(...args) {2301return function (...ignoredArgs/*, callback*/) {2302var callback = ignoredArgs.pop();2303return callback(null, ...args);2304};2305}23062307function _createTester(check, getResult) {2308return (eachfn, arr, _iteratee, cb) => {2309var testPassed = false;2310var testResult;2311const iteratee = wrapAsync(_iteratee);2312eachfn(arr, (value, _, callback) => {2313iteratee(value, (err, result) => {2314if (err || err === false) return callback(err);23152316if (check(result) && !testResult) {2317testPassed = true;2318testResult = getResult(true, value);2319return callback(null, breakLoop);2320}2321callback();2322});2323}, err => {2324if (err) return cb(err);2325cb(null, testPassed ? testResult : getResult(false));2326});2327};2328}23292330/**2331* Returns the first value in `coll` that passes an async truth test. The2332* `iteratee` is applied in parallel, meaning the first iteratee to return2333* `true` will fire the detect `callback` with that result. That means the2334* result might not be the first item in the original `coll` (in terms of order)2335* that passes the test.23362337* If order within the original `coll` is important, then look at2338* [`detectSeries`]{@link module:Collections.detectSeries}.2339*2340* @name detect2341* @static2342* @memberOf module:Collections2343* @method2344* @alias find2345* @category Collections2346* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2347* @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.2348* The iteratee must complete with a boolean value as its result.2349* Invoked with (item, callback).2350* @param {Function} [callback] - A callback which is called as soon as any2351* iteratee returns `true`, or after all the `iteratee` functions have finished.2352* Result will be the first item in the array that passes the truth test2353* (iteratee) or the value `undefined` if none passed. Invoked with2354* (err, result).2355* @returns {Promise} a promise, if a callback is omitted2356* @example2357*2358* // dir1 is a directory that contains file1.txt, file2.txt2359* // dir2 is a directory that contains file3.txt, file4.txt2360* // dir3 is a directory that contains file5.txt2361*2362* // asynchronous function that checks if a file exists2363* function fileExists(file, callback) {2364* fs.access(file, fs.constants.F_OK, (err) => {2365* callback(null, !err);2366* });2367* }2368*2369* async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists,2370* function(err, result) {2371* console.log(result);2372* // dir1/file1.txt2373* // result now equals the first file in the list that exists2374* }2375*);2376*2377* // Using Promises2378* async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists)2379* .then(result => {2380* console.log(result);2381* // dir1/file1.txt2382* // result now equals the first file in the list that exists2383* }).catch(err => {2384* console.log(err);2385* });2386*2387* // Using async/await2388* async () => {2389* try {2390* let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists);2391* console.log(result);2392* // dir1/file1.txt2393* // result now equals the file in the list that exists2394* }2395* catch (err) {2396* console.log(err);2397* }2398* }2399*2400*/2401function detect(coll, iteratee, callback) {2402return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback)2403}2404var detect$1 = awaitify(detect, 3);24052406/**2407* The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a2408* time.2409*2410* @name detectLimit2411* @static2412* @memberOf module:Collections2413* @method2414* @see [async.detect]{@link module:Collections.detect}2415* @alias findLimit2416* @category Collections2417* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2418* @param {number} limit - The maximum number of async operations at a time.2419* @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.2420* The iteratee must complete with a boolean value as its result.2421* Invoked with (item, callback).2422* @param {Function} [callback] - A callback which is called as soon as any2423* iteratee returns `true`, or after all the `iteratee` functions have finished.2424* Result will be the first item in the array that passes the truth test2425* (iteratee) or the value `undefined` if none passed. Invoked with2426* (err, result).2427* @returns {Promise} a promise, if a callback is omitted2428*/2429function detectLimit(coll, limit, iteratee, callback) {2430return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback)2431}2432var detectLimit$1 = awaitify(detectLimit, 4);24332434/**2435* The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.2436*2437* @name detectSeries2438* @static2439* @memberOf module:Collections2440* @method2441* @see [async.detect]{@link module:Collections.detect}2442* @alias findSeries2443* @category Collections2444* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2445* @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.2446* The iteratee must complete with a boolean value as its result.2447* Invoked with (item, callback).2448* @param {Function} [callback] - A callback which is called as soon as any2449* iteratee returns `true`, or after all the `iteratee` functions have finished.2450* Result will be the first item in the array that passes the truth test2451* (iteratee) or the value `undefined` if none passed. Invoked with2452* (err, result).2453* @returns {Promise} a promise, if a callback is omitted2454*/2455function detectSeries(coll, iteratee, callback) {2456return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback)2457}24582459var detectSeries$1 = awaitify(detectSeries, 3);24602461function consoleFunc(name) {2462return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => {2463/* istanbul ignore else */2464if (typeof console === 'object') {2465/* istanbul ignore else */2466if (err) {2467/* istanbul ignore else */2468if (console.error) {2469console.error(err);2470}2471} else if (console[name]) { /* istanbul ignore else */2472resultArgs.forEach(x => console[name](x));2473}2474}2475})2476}24772478/**2479* Logs the result of an [`async` function]{@link AsyncFunction} to the2480* `console` using `console.dir` to display the properties of the resulting object.2481* Only works in Node.js or in browsers that support `console.dir` and2482* `console.error` (such as FF and Chrome).2483* If multiple arguments are returned from the async function,2484* `console.dir` is called on each argument in order.2485*2486* @name dir2487* @static2488* @memberOf module:Utils2489* @method2490* @category Util2491* @param {AsyncFunction} function - The function you want to eventually apply2492* all arguments to.2493* @param {...*} arguments... - Any number of arguments to apply to the function.2494* @example2495*2496* // in a module2497* var hello = function(name, callback) {2498* setTimeout(function() {2499* callback(null, {hello: name});2500* }, 1000);2501* };2502*2503* // in the node repl2504* node> async.dir(hello, 'world');2505* {hello: 'world'}2506*/2507var dir = consoleFunc('dir');25082509/**2510* The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in2511* the order of operations, the arguments `test` and `iteratee` are switched.2512*2513* `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.2514*2515* @name doWhilst2516* @static2517* @memberOf module:ControlFlow2518* @method2519* @see [async.whilst]{@link module:ControlFlow.whilst}2520* @category Control Flow2521* @param {AsyncFunction} iteratee - A function which is called each time `test`2522* passes. Invoked with (callback).2523* @param {AsyncFunction} test - asynchronous truth test to perform after each2524* execution of `iteratee`. Invoked with (...args, callback), where `...args` are the2525* non-error args from the previous callback of `iteratee`.2526* @param {Function} [callback] - A callback which is called after the test2527* function has failed and repeated execution of `iteratee` has stopped.2528* `callback` will be passed an error and any arguments passed to the final2529* `iteratee`'s callback. Invoked with (err, [results]);2530* @returns {Promise} a promise, if no callback is passed2531*/2532function doWhilst(iteratee, test, callback) {2533callback = onlyOnce(callback);2534var _fn = wrapAsync(iteratee);2535var _test = wrapAsync(test);2536var results;25372538function next(err, ...args) {2539if (err) return callback(err);2540if (err === false) return;2541results = args;2542_test(...args, check);2543}25442545function check(err, truth) {2546if (err) return callback(err);2547if (err === false) return;2548if (!truth) return callback(null, ...results);2549_fn(next);2550}25512552return check(null, true);2553}25542555var doWhilst$1 = awaitify(doWhilst, 3);25562557/**2558* Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the2559* argument ordering differs from `until`.2560*2561* @name doUntil2562* @static2563* @memberOf module:ControlFlow2564* @method2565* @see [async.doWhilst]{@link module:ControlFlow.doWhilst}2566* @category Control Flow2567* @param {AsyncFunction} iteratee - An async function which is called each time2568* `test` fails. Invoked with (callback).2569* @param {AsyncFunction} test - asynchronous truth test to perform after each2570* execution of `iteratee`. Invoked with (...args, callback), where `...args` are the2571* non-error args from the previous callback of `iteratee`2572* @param {Function} [callback] - A callback which is called after the test2573* function has passed and repeated execution of `iteratee` has stopped. `callback`2574* will be passed an error and any arguments passed to the final `iteratee`'s2575* callback. Invoked with (err, [results]);2576* @returns {Promise} a promise, if no callback is passed2577*/2578function doUntil(iteratee, test, callback) {2579const _test = wrapAsync(test);2580return doWhilst$1(iteratee, (...args) => {2581const cb = args.pop();2582_test(...args, (err, truth) => cb (err, !truth));2583}, callback);2584}25852586function _withoutIndex(iteratee) {2587return (value, index, callback) => iteratee(value, callback);2588}25892590/**2591* Applies the function `iteratee` to each item in `coll`, in parallel.2592* The `iteratee` is called with an item from the list, and a callback for when2593* it has finished. If the `iteratee` passes an error to its `callback`, the2594* main `callback` (for the `each` function) is immediately called with the2595* error.2596*2597* Note, that since this function applies `iteratee` to each item in parallel,2598* there is no guarantee that the iteratee functions will complete in order.2599*2600* @name each2601* @static2602* @memberOf module:Collections2603* @method2604* @alias forEach2605* @category Collection2606* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2607* @param {AsyncFunction} iteratee - An async function to apply to2608* each item in `coll`. Invoked with (item, callback).2609* The array index is not passed to the iteratee.2610* If you need the index, use `eachOf`.2611* @param {Function} [callback] - A callback which is called when all2612* `iteratee` functions have finished, or an error occurs. Invoked with (err).2613* @returns {Promise} a promise, if a callback is omitted2614* @example2615*2616* // dir1 is a directory that contains file1.txt, file2.txt2617* // dir2 is a directory that contains file3.txt, file4.txt2618* // dir3 is a directory that contains file5.txt2619* // dir4 does not exist2620*2621* const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];2622* const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];2623*2624* // asynchronous function that deletes a file2625* const deleteFile = function(file, callback) {2626* fs.unlink(file, callback);2627* };2628*2629* // Using callbacks2630* async.each(fileList, deleteFile, function(err) {2631* if( err ) {2632* console.log(err);2633* } else {2634* console.log('All files have been deleted successfully');2635* }2636* });2637*2638* // Error Handling2639* async.each(withMissingFileList, deleteFile, function(err){2640* console.log(err);2641* // [ Error: ENOENT: no such file or directory ]2642* // since dir4/file2.txt does not exist2643* // dir1/file1.txt could have been deleted2644* });2645*2646* // Using Promises2647* async.each(fileList, deleteFile)2648* .then( () => {2649* console.log('All files have been deleted successfully');2650* }).catch( err => {2651* console.log(err);2652* });2653*2654* // Error Handling2655* async.each(fileList, deleteFile)2656* .then( () => {2657* console.log('All files have been deleted successfully');2658* }).catch( err => {2659* console.log(err);2660* // [ Error: ENOENT: no such file or directory ]2661* // since dir4/file2.txt does not exist2662* // dir1/file1.txt could have been deleted2663* });2664*2665* // Using async/await2666* async () => {2667* try {2668* await async.each(files, deleteFile);2669* }2670* catch (err) {2671* console.log(err);2672* }2673* }2674*2675* // Error Handling2676* async () => {2677* try {2678* await async.each(withMissingFileList, deleteFile);2679* }2680* catch (err) {2681* console.log(err);2682* // [ Error: ENOENT: no such file or directory ]2683* // since dir4/file2.txt does not exist2684* // dir1/file1.txt could have been deleted2685* }2686* }2687*2688*/2689function eachLimit(coll, iteratee, callback) {2690return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback);2691}26922693var each = awaitify(eachLimit, 3);26942695/**2696* The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.2697*2698* @name eachLimit2699* @static2700* @memberOf module:Collections2701* @method2702* @see [async.each]{@link module:Collections.each}2703* @alias forEachLimit2704* @category Collection2705* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2706* @param {number} limit - The maximum number of async operations at a time.2707* @param {AsyncFunction} iteratee - An async function to apply to each item in2708* `coll`.2709* The array index is not passed to the iteratee.2710* If you need the index, use `eachOfLimit`.2711* Invoked with (item, callback).2712* @param {Function} [callback] - A callback which is called when all2713* `iteratee` functions have finished, or an error occurs. Invoked with (err).2714* @returns {Promise} a promise, if a callback is omitted2715*/2716function eachLimit$1(coll, limit, iteratee, callback) {2717return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);2718}2719var eachLimit$2 = awaitify(eachLimit$1, 4);27202721/**2722* The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.2723*2724* Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item2725* in series and therefore the iteratee functions will complete in order.27262727* @name eachSeries2728* @static2729* @memberOf module:Collections2730* @method2731* @see [async.each]{@link module:Collections.each}2732* @alias forEachSeries2733* @category Collection2734* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2735* @param {AsyncFunction} iteratee - An async function to apply to each2736* item in `coll`.2737* The array index is not passed to the iteratee.2738* If you need the index, use `eachOfSeries`.2739* Invoked with (item, callback).2740* @param {Function} [callback] - A callback which is called when all2741* `iteratee` functions have finished, or an error occurs. Invoked with (err).2742* @returns {Promise} a promise, if a callback is omitted2743*/2744function eachSeries(coll, iteratee, callback) {2745return eachLimit$2(coll, 1, iteratee, callback)2746}2747var eachSeries$1 = awaitify(eachSeries, 3);27482749/**2750* Wrap an async function and ensure it calls its callback on a later tick of2751* the event loop. If the function already calls its callback on a next tick,2752* no extra deferral is added. This is useful for preventing stack overflows2753* (`RangeError: Maximum call stack size exceeded`) and generally keeping2754* [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)2755* contained. ES2017 `async` functions are returned as-is -- they are immune2756* to Zalgo's corrupting influences, as they always resolve on a later tick.2757*2758* @name ensureAsync2759* @static2760* @memberOf module:Utils2761* @method2762* @category Util2763* @param {AsyncFunction} fn - an async function, one that expects a node-style2764* callback as its last argument.2765* @returns {AsyncFunction} Returns a wrapped function with the exact same call2766* signature as the function passed in.2767* @example2768*2769* function sometimesAsync(arg, callback) {2770* if (cache[arg]) {2771* return callback(null, cache[arg]); // this would be synchronous!!2772* } else {2773* doSomeIO(arg, callback); // this IO would be asynchronous2774* }2775* }2776*2777* // this has a risk of stack overflows if many results are cached in a row2778* async.mapSeries(args, sometimesAsync, done);2779*2780* // this will defer sometimesAsync's callback if necessary,2781* // preventing stack overflows2782* async.mapSeries(args, async.ensureAsync(sometimesAsync), done);2783*/2784function ensureAsync(fn) {2785if (isAsync(fn)) return fn;2786return function (...args/*, callback*/) {2787var callback = args.pop();2788var sync = true;2789args.push((...innerArgs) => {2790if (sync) {2791setImmediate$1(() => callback(...innerArgs));2792} else {2793callback(...innerArgs);2794}2795});2796fn.apply(this, args);2797sync = false;2798};2799}28002801/**2802* Returns `true` if every element in `coll` satisfies an async test. If any2803* iteratee call returns `false`, the main `callback` is immediately called.2804*2805* @name every2806* @static2807* @memberOf module:Collections2808* @method2809* @alias all2810* @category Collection2811* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2812* @param {AsyncFunction} iteratee - An async truth test to apply to each item2813* in the collection in parallel.2814* The iteratee must complete with a boolean result value.2815* Invoked with (item, callback).2816* @param {Function} [callback] - A callback which is called after all the2817* `iteratee` functions have finished. Result will be either `true` or `false`2818* depending on the values of the async tests. Invoked with (err, result).2819* @returns {Promise} a promise, if no callback provided2820* @example2821*2822* // dir1 is a directory that contains file1.txt, file2.txt2823* // dir2 is a directory that contains file3.txt, file4.txt2824* // dir3 is a directory that contains file5.txt2825* // dir4 does not exist2826*2827* const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt'];2828* const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];2829*2830* // asynchronous function that checks if a file exists2831* function fileExists(file, callback) {2832* fs.access(file, fs.constants.F_OK, (err) => {2833* callback(null, !err);2834* });2835* }2836*2837* // Using callbacks2838* async.every(fileList, fileExists, function(err, result) {2839* console.log(result);2840* // true2841* // result is true since every file exists2842* });2843*2844* async.every(withMissingFileList, fileExists, function(err, result) {2845* console.log(result);2846* // false2847* // result is false since NOT every file exists2848* });2849*2850* // Using Promises2851* async.every(fileList, fileExists)2852* .then( result => {2853* console.log(result);2854* // true2855* // result is true since every file exists2856* }).catch( err => {2857* console.log(err);2858* });2859*2860* async.every(withMissingFileList, fileExists)2861* .then( result => {2862* console.log(result);2863* // false2864* // result is false since NOT every file exists2865* }).catch( err => {2866* console.log(err);2867* });2868*2869* // Using async/await2870* async () => {2871* try {2872* let result = await async.every(fileList, fileExists);2873* console.log(result);2874* // true2875* // result is true since every file exists2876* }2877* catch (err) {2878* console.log(err);2879* }2880* }2881*2882* async () => {2883* try {2884* let result = await async.every(withMissingFileList, fileExists);2885* console.log(result);2886* // false2887* // result is false since NOT every file exists2888* }2889* catch (err) {2890* console.log(err);2891* }2892* }2893*2894*/2895function every(coll, iteratee, callback) {2896return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback)2897}2898var every$1 = awaitify(every, 3);28992900/**2901* The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.2902*2903* @name everyLimit2904* @static2905* @memberOf module:Collections2906* @method2907* @see [async.every]{@link module:Collections.every}2908* @alias allLimit2909* @category Collection2910* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2911* @param {number} limit - The maximum number of async operations at a time.2912* @param {AsyncFunction} iteratee - An async truth test to apply to each item2913* in the collection in parallel.2914* The iteratee must complete with a boolean result value.2915* Invoked with (item, callback).2916* @param {Function} [callback] - A callback which is called after all the2917* `iteratee` functions have finished. Result will be either `true` or `false`2918* depending on the values of the async tests. Invoked with (err, result).2919* @returns {Promise} a promise, if no callback provided2920*/2921function everyLimit(coll, limit, iteratee, callback) {2922return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback)2923}2924var everyLimit$1 = awaitify(everyLimit, 4);29252926/**2927* The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.2928*2929* @name everySeries2930* @static2931* @memberOf module:Collections2932* @method2933* @see [async.every]{@link module:Collections.every}2934* @alias allSeries2935* @category Collection2936* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.2937* @param {AsyncFunction} iteratee - An async truth test to apply to each item2938* in the collection in series.2939* The iteratee must complete with a boolean result value.2940* Invoked with (item, callback).2941* @param {Function} [callback] - A callback which is called after all the2942* `iteratee` functions have finished. Result will be either `true` or `false`2943* depending on the values of the async tests. Invoked with (err, result).2944* @returns {Promise} a promise, if no callback provided2945*/2946function everySeries(coll, iteratee, callback) {2947return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback)2948}2949var everySeries$1 = awaitify(everySeries, 3);29502951function filterArray(eachfn, arr, iteratee, callback) {2952var truthValues = new Array(arr.length);2953eachfn(arr, (x, index, iterCb) => {2954iteratee(x, (err, v) => {2955truthValues[index] = !!v;2956iterCb(err);2957});2958}, err => {2959if (err) return callback(err);2960var results = [];2961for (var i = 0; i < arr.length; i++) {2962if (truthValues[i]) results.push(arr[i]);2963}2964callback(null, results);2965});2966}29672968function filterGeneric(eachfn, coll, iteratee, callback) {2969var results = [];2970eachfn(coll, (x, index, iterCb) => {2971iteratee(x, (err, v) => {2972if (err) return iterCb(err);2973if (v) {2974results.push({index, value: x});2975}2976iterCb(err);2977});2978}, err => {2979if (err) return callback(err);2980callback(null, results2981.sort((a, b) => a.index - b.index)2982.map(v => v.value));2983});2984}29852986function _filter(eachfn, coll, iteratee, callback) {2987var filter = isArrayLike(coll) ? filterArray : filterGeneric;2988return filter(eachfn, coll, wrapAsync(iteratee), callback);2989}29902991/**2992* Returns a new array of all the values in `coll` which pass an async truth2993* test. This operation is performed in parallel, but the results array will be2994* in the same order as the original.2995*2996* @name filter2997* @static2998* @memberOf module:Collections2999* @method3000* @alias select3001* @category Collection3002* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.3003* @param {Function} iteratee - A truth test to apply to each item in `coll`.3004* The `iteratee` is passed a `callback(err, truthValue)`, which must be called3005* with a boolean argument once it has completed. Invoked with (item, callback).3006* @param {Function} [callback] - A callback which is called after all the3007* `iteratee` functions have finished. Invoked with (err, results).3008* @returns {Promise} a promise, if no callback provided3009* @example3010*3011* // dir1 is a directory that contains file1.txt, file2.txt3012* // dir2 is a directory that contains file3.txt, file4.txt3013* // dir3 is a directory that contains file5.txt3014*3015* const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];3016*3017* // asynchronous function that checks if a file exists3018* function fileExists(file, callback) {3019* fs.access(file, fs.constants.F_OK, (err) => {3020* callback(null, !err);3021* });3022* }3023*3024* // Using callbacks3025* async.filter(files, fileExists, function(err, results) {3026* if(err) {3027* console.log(err);3028* } else {3029* console.log(results);3030* // [ 'dir1/file1.txt', 'dir2/file3.txt' ]3031* // results is now an array of the existing files3032* }3033* });3034*3035* // Using Promises3036* async.filter(files, fileExists)3037* .then(results => {3038* console.log(results);3039* // [ 'dir1/file1.txt', 'dir2/file3.txt' ]3040* // results is now an array of the existing files3041* }).catch(err => {3042* console.log(err);3043* });3044*3045* // Using async/await3046* async () => {3047* try {3048* let results = await async.filter(files, fileExists);3049* console.log(results);3050* // [ 'dir1/file1.txt', 'dir2/file3.txt' ]3051* // results is now an array of the existing files3052* }3053* catch (err) {3054* console.log(err);3055* }3056* }3057*3058*/3059function filter (coll, iteratee, callback) {3060return _filter(eachOf$1, coll, iteratee, callback)3061}3062var filter$1 = awaitify(filter, 3);30633064/**3065* The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a3066* time.3067*3068* @name filterLimit3069* @static3070* @memberOf module:Collections3071* @method3072* @see [async.filter]{@link module:Collections.filter}3073* @alias selectLimit3074* @category Collection3075* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.3076* @param {number} limit - The maximum number of async operations at a time.3077* @param {Function} iteratee - A truth test to apply to each item in `coll`.3078* The `iteratee` is passed a `callback(err, truthValue)`, which must be called3079* with a boolean argument once it has completed. Invoked with (item, callback).3080* @param {Function} [callback] - A callback which is called after all the3081* `iteratee` functions have finished. Invoked with (err, results).3082* @returns {Promise} a promise, if no callback provided3083*/3084function filterLimit (coll, limit, iteratee, callback) {3085return _filter(eachOfLimit(limit), coll, iteratee, callback)3086}3087var filterLimit$1 = awaitify(filterLimit, 4);30883089/**3090* The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.3091*3092* @name filterSeries3093* @static3094* @memberOf module:Collections3095* @method3096* @see [async.filter]{@link module:Collections.filter}3097* @alias selectSeries3098* @category Collection3099* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.3100* @param {Function} iteratee - A truth test to apply to each item in `coll`.3101* The `iteratee` is passed a `callback(err, truthValue)`, which must be called3102* with a boolean argument once it has completed. Invoked with (item, callback).3103* @param {Function} [callback] - A callback which is called after all the3104* `iteratee` functions have finished. Invoked with (err, results)3105* @returns {Promise} a promise, if no callback provided3106*/3107function filterSeries (coll, iteratee, callback) {3108return _filter(eachOfSeries$1, coll, iteratee, callback)3109}3110var filterSeries$1 = awaitify(filterSeries, 3);31113112/**3113* Calls the asynchronous function `fn` with a callback parameter that allows it3114* to call itself again, in series, indefinitely.31153116* If an error is passed to the callback then `errback` is called with the3117* error, and execution stops, otherwise it will never be called.3118*3119* @name forever3120* @static3121* @memberOf module:ControlFlow3122* @method3123* @category Control Flow3124* @param {AsyncFunction} fn - an async function to call repeatedly.3125* Invoked with (next).3126* @param {Function} [errback] - when `fn` passes an error to it's callback,3127* this function will be called, and execution stops. Invoked with (err).3128* @returns {Promise} a promise that rejects if an error occurs and an errback3129* is not passed3130* @example3131*3132* async.forever(3133* function(next) {3134* // next is suitable for passing to things that need a callback(err [, whatever]);3135* // it will result in this function being called again.3136* },3137* function(err) {3138* // if next is called with a value in its first parameter, it will appear3139* // in here as 'err', and execution will stop.3140* }3141* );3142*/3143function forever(fn, errback) {3144var done = onlyOnce(errback);3145var task = wrapAsync(ensureAsync(fn));31463147function next(err) {3148if (err) return done(err);3149if (err === false) return;3150task(next);3151}3152return next();3153}3154var forever$1 = awaitify(forever, 2);31553156/**3157* The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.3158*3159* @name groupByLimit3160* @static3161* @memberOf module:Collections3162* @method3163* @see [async.groupBy]{@link module:Collections.groupBy}3164* @category Collection3165* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.3166* @param {number} limit - The maximum number of async operations at a time.3167* @param {AsyncFunction} iteratee - An async function to apply to each item in3168* `coll`.3169* The iteratee should complete with a `key` to group the value under.3170* Invoked with (value, callback).3171* @param {Function} [callback] - A callback which is called when all `iteratee`3172* functions have finished, or an error occurs. Result is an `Object` whoses3173* properties are arrays of values which returned the corresponding key.3174* @returns {Promise} a promise, if no callback is passed3175*/3176function groupByLimit(coll, limit, iteratee, callback) {3177var _iteratee = wrapAsync(iteratee);3178return mapLimit$1(coll, limit, (val, iterCb) => {3179_iteratee(val, (err, key) => {3180if (err) return iterCb(err);3181return iterCb(err, {key, val});3182});3183}, (err, mapResults) => {3184var result = {};3185// from MDN, handle object having an `hasOwnProperty` prop3186var {hasOwnProperty} = Object.prototype;31873188for (var i = 0; i < mapResults.length; i++) {3189if (mapResults[i]) {3190var {key} = mapResults[i];3191var {val} = mapResults[i];31923193if (hasOwnProperty.call(result, key)) {3194result[key].push(val);3195} else {3196result[key] = [val];3197}3198}3199}32003201return callback(err, result);3202});3203}32043205var groupByLimit$1 = awaitify(groupByLimit, 4);32063207/**3208* Returns a new object, where each value corresponds to an array of items, from3209* `coll`, that returned the corresponding key. That is, the keys of the object3210* correspond to the values passed to the `iteratee` callback.3211*3212* Note: Since this function applies the `iteratee` to each item in parallel,3213* there is no guarantee that the `iteratee` functions will complete in order.3214* However, the values for each key in the `result` will be in the same order as3215* the original `coll`. For Objects, the values will roughly be in the order of3216* the original Objects' keys (but this can vary across JavaScript engines).3217*3218* @name groupBy3219* @static3220* @memberOf module:Collections3221* @method3222* @category Collection3223* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.3224* @param {AsyncFunction} iteratee - An async function to apply to each item in3225* `coll`.3226* The iteratee should complete with a `key` to group the value under.3227* Invoked with (value, callback).3228* @param {Function} [callback] - A callback which is called when all `iteratee`3229* functions have finished, or an error occurs. Result is an `Object` whoses3230* properties are arrays of values which returned the corresponding key.3231* @returns {Promise} a promise, if no callback is passed3232* @example3233*3234* // dir1 is a directory that contains file1.txt, file2.txt3235* // dir2 is a directory that contains file3.txt, file4.txt3236* // dir3 is a directory that contains file5.txt3237* // dir4 does not exist3238*3239* const files = ['dir1/file1.txt','dir2','dir4']3240*3241* // asynchronous function that detects file type as none, file, or directory3242* function detectFile(file, callback) {3243* fs.stat(file, function(err, stat) {3244* if (err) {3245* return callback(null, 'none');3246* }3247* callback(null, stat.isDirectory() ? 'directory' : 'file');3248* });3249* }3250*3251* //Using callbacks3252* async.groupBy(files, detectFile, function(err, result) {3253* if(err) {3254* console.log(err);3255* } else {3256* console.log(result);3257* // {3258* // file: [ 'dir1/file1.txt' ],3259* // none: [ 'dir4' ],3260* // directory: [ 'dir2']3261* // }3262* // result is object containing the files grouped by type3263* }3264* });3265*3266* // Using Promises3267* async.groupBy(files, detectFile)3268* .then( result => {3269* console.log(result);3270* // {3271* // file: [ 'dir1/file1.txt' ],3272* // none: [ 'dir4' ],3273* // directory: [ 'dir2']3274* // }3275* // result is object containing the files grouped by type3276* }).catch( err => {3277* console.log(err);3278* });3279*3280* // Using async/await3281* async () => {3282* try {3283* let result = await async.groupBy(files, detectFile);3284* console.log(result);3285* // {3286* // file: [ 'dir1/file1.txt' ],3287* // none: [ 'dir4' ],3288* // directory: [ 'dir2']3289* // }3290* // result is object containing the files grouped by type3291* }3292* catch (err) {3293* console.log(err);3294* }3295* }3296*3297*/3298function groupBy (coll, iteratee, callback) {3299return groupByLimit$1(coll, Infinity, iteratee, callback)3300}33013302/**3303* The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.3304*3305* @name groupBySeries3306* @static3307* @memberOf module:Collections3308* @method3309* @see [async.groupBy]{@link module:Collections.groupBy}3310* @category Collection3311* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.3312* @param {AsyncFunction} iteratee - An async function to apply to each item in3313* `coll`.3314* The iteratee should complete with a `key` to group the value under.3315* Invoked with (value, callback).3316* @param {Function} [callback] - A callback which is called when all `iteratee`3317* functions have finished, or an error occurs. Result is an `Object` whose3318* properties are arrays of values which returned the corresponding key.3319* @returns {Promise} a promise, if no callback is passed3320*/3321function groupBySeries (coll, iteratee, callback) {3322return groupByLimit$1(coll, 1, iteratee, callback)3323}33243325/**3326* Logs the result of an `async` function to the `console`. Only works in3327* Node.js or in browsers that support `console.log` and `console.error` (such3328* as FF and Chrome). If multiple arguments are returned from the async3329* function, `console.log` is called on each argument in order.3330*3331* @name log3332* @static3333* @memberOf module:Utils3334* @method3335* @category Util3336* @param {AsyncFunction} function - The function you want to eventually apply3337* all arguments to.3338* @param {...*} arguments... - Any number of arguments to apply to the function.3339* @example3340*3341* // in a module3342* var hello = function(name, callback) {3343* setTimeout(function() {3344* callback(null, 'hello ' + name);3345* }, 1000);3346* };3347*3348* // in the node repl3349* node> async.log(hello, 'world');3350* 'hello world'3351*/3352var log = consoleFunc('log');33533354/**3355* The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a3356* time.3357*3358* @name mapValuesLimit3359* @static3360* @memberOf module:Collections3361* @method3362* @see [async.mapValues]{@link module:Collections.mapValues}3363* @category Collection3364* @param {Object} obj - A collection to iterate over.3365* @param {number} limit - The maximum number of async operations at a time.3366* @param {AsyncFunction} iteratee - A function to apply to each value and key3367* in `coll`.3368* The iteratee should complete with the transformed value as its result.3369* Invoked with (value, key, callback).3370* @param {Function} [callback] - A callback which is called when all `iteratee`3371* functions have finished, or an error occurs. `result` is a new object consisting3372* of each key from `obj`, with each transformed value on the right-hand side.3373* Invoked with (err, result).3374* @returns {Promise} a promise, if no callback is passed3375*/3376function mapValuesLimit(obj, limit, iteratee, callback) {3377callback = once(callback);3378var newObj = {};3379var _iteratee = wrapAsync(iteratee);3380return eachOfLimit(limit)(obj, (val, key, next) => {3381_iteratee(val, key, (err, result) => {3382if (err) return next(err);3383newObj[key] = result;3384next(err);3385});3386}, err => callback(err, newObj));3387}33883389var mapValuesLimit$1 = awaitify(mapValuesLimit, 4);33903391/**3392* A relative of [`map`]{@link module:Collections.map}, designed for use with objects.3393*3394* Produces a new Object by mapping each value of `obj` through the `iteratee`3395* function. The `iteratee` is called each `value` and `key` from `obj` and a3396* callback for when it has finished processing. Each of these callbacks takes3397* two arguments: an `error`, and the transformed item from `obj`. If `iteratee`3398* passes an error to its callback, the main `callback` (for the `mapValues`3399* function) is immediately called with the error.3400*3401* Note, the order of the keys in the result is not guaranteed. The keys will3402* be roughly in the order they complete, (but this is very engine-specific)3403*3404* @name mapValues3405* @static3406* @memberOf module:Collections3407* @method3408* @category Collection3409* @param {Object} obj - A collection to iterate over.3410* @param {AsyncFunction} iteratee - A function to apply to each value and key3411* in `coll`.3412* The iteratee should complete with the transformed value as its result.3413* Invoked with (value, key, callback).3414* @param {Function} [callback] - A callback which is called when all `iteratee`3415* functions have finished, or an error occurs. `result` is a new object consisting3416* of each key from `obj`, with each transformed value on the right-hand side.3417* Invoked with (err, result).3418* @returns {Promise} a promise, if no callback is passed3419* @example3420*3421* // file1.txt is a file that is 1000 bytes in size3422* // file2.txt is a file that is 2000 bytes in size3423* // file3.txt is a file that is 3000 bytes in size3424* // file4.txt does not exist3425*3426* const fileMap = {3427* f1: 'file1.txt',3428* f2: 'file2.txt',3429* f3: 'file3.txt'3430* };3431*3432* const withMissingFileMap = {3433* f1: 'file1.txt',3434* f2: 'file2.txt',3435* f3: 'file4.txt'3436* };3437*3438* // asynchronous function that returns the file size in bytes3439* function getFileSizeInBytes(file, key, callback) {3440* fs.stat(file, function(err, stat) {3441* if (err) {3442* return callback(err);3443* }3444* callback(null, stat.size);3445* });3446* }3447*3448* // Using callbacks3449* async.mapValues(fileMap, getFileSizeInBytes, function(err, result) {3450* if (err) {3451* console.log(err);3452* } else {3453* console.log(result);3454* // result is now a map of file size in bytes for each file, e.g.3455* // {3456* // f1: 1000,3457* // f2: 2000,3458* // f3: 30003459* // }3460* }3461* });3462*3463* // Error handling3464* async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) {3465* if (err) {3466* console.log(err);3467* // [ Error: ENOENT: no such file or directory ]3468* } else {3469* console.log(result);3470* }3471* });3472*3473* // Using Promises3474* async.mapValues(fileMap, getFileSizeInBytes)3475* .then( result => {3476* console.log(result);3477* // result is now a map of file size in bytes for each file, e.g.3478* // {3479* // f1: 1000,3480* // f2: 2000,3481* // f3: 30003482* // }3483* }).catch (err => {3484* console.log(err);3485* });3486*3487* // Error Handling3488* async.mapValues(withMissingFileMap, getFileSizeInBytes)3489* .then( result => {3490* console.log(result);3491* }).catch (err => {3492* console.log(err);3493* // [ Error: ENOENT: no such file or directory ]3494* });3495*3496* // Using async/await3497* async () => {3498* try {3499* let result = await async.mapValues(fileMap, getFileSizeInBytes);3500* console.log(result);3501* // result is now a map of file size in bytes for each file, e.g.3502* // {3503* // f1: 1000,3504* // f2: 2000,3505* // f3: 30003506* // }3507* }3508* catch (err) {3509* console.log(err);3510* }3511* }3512*3513* // Error Handling3514* async () => {3515* try {3516* let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes);3517* console.log(result);3518* }3519* catch (err) {3520* console.log(err);3521* // [ Error: ENOENT: no such file or directory ]3522* }3523* }3524*3525*/3526function mapValues(obj, iteratee, callback) {3527return mapValuesLimit$1(obj, Infinity, iteratee, callback)3528}35293530/**3531* The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.3532*3533* @name mapValuesSeries3534* @static3535* @memberOf module:Collections3536* @method3537* @see [async.mapValues]{@link module:Collections.mapValues}3538* @category Collection3539* @param {Object} obj - A collection to iterate over.3540* @param {AsyncFunction} iteratee - A function to apply to each value and key3541* in `coll`.3542* The iteratee should complete with the transformed value as its result.3543* Invoked with (value, key, callback).3544* @param {Function} [callback] - A callback which is called when all `iteratee`3545* functions have finished, or an error occurs. `result` is a new object consisting3546* of each key from `obj`, with each transformed value on the right-hand side.3547* Invoked with (err, result).3548* @returns {Promise} a promise, if no callback is passed3549*/3550function mapValuesSeries(obj, iteratee, callback) {3551return mapValuesLimit$1(obj, 1, iteratee, callback)3552}35533554/**3555* Caches the results of an async function. When creating a hash to store3556* function results against, the callback is omitted from the hash and an3557* optional hash function can be used.3558*3559* **Note: if the async function errs, the result will not be cached and3560* subsequent calls will call the wrapped function.**3561*3562* If no hash function is specified, the first argument is used as a hash key,3563* which may work reasonably if it is a string or a data type that converts to a3564* distinct string. Note that objects and arrays will not behave reasonably.3565* Neither will cases where the other arguments are significant. In such cases,3566* specify your own hash function.3567*3568* The cache of results is exposed as the `memo` property of the function3569* returned by `memoize`.3570*3571* @name memoize3572* @static3573* @memberOf module:Utils3574* @method3575* @category Util3576* @param {AsyncFunction} fn - The async function to proxy and cache results from.3577* @param {Function} hasher - An optional function for generating a custom hash3578* for storing results. It has all the arguments applied to it apart from the3579* callback, and must be synchronous.3580* @returns {AsyncFunction} a memoized version of `fn`3581* @example3582*3583* var slow_fn = function(name, callback) {3584* // do something3585* callback(null, result);3586* };3587* var fn = async.memoize(slow_fn);3588*3589* // fn can now be used as if it were slow_fn3590* fn('some name', function() {3591* // callback3592* });3593*/3594function memoize(fn, hasher = v => v) {3595var memo = Object.create(null);3596var queues = Object.create(null);3597var _fn = wrapAsync(fn);3598var memoized = initialParams((args, callback) => {3599var key = hasher(...args);3600if (key in memo) {3601setImmediate$1(() => callback(null, ...memo[key]));3602} else if (key in queues) {3603queues[key].push(callback);3604} else {3605queues[key] = [callback];3606_fn(...args, (err, ...resultArgs) => {3607// #1465 don't memoize if an error occurred3608if (!err) {3609memo[key] = resultArgs;3610}3611var q = queues[key];3612delete queues[key];3613for (var i = 0, l = q.length; i < l; i++) {3614q[i](err, ...resultArgs);3615}3616});3617}3618});3619memoized.memo = memo;3620memoized.unmemoized = fn;3621return memoized;3622}36233624/* istanbul ignore file */36253626/**3627* Calls `callback` on a later loop around the event loop. In Node.js this just3628* calls `process.nextTick`. In the browser it will use `setImmediate` if3629* available, otherwise `setTimeout(callback, 0)`, which means other higher3630* priority events may precede the execution of `callback`.3631*3632* This is used internally for browser-compatibility purposes.3633*3634* @name nextTick3635* @static3636* @memberOf module:Utils3637* @method3638* @see [async.setImmediate]{@link module:Utils.setImmediate}3639* @category Util3640* @param {Function} callback - The function to call on a later loop around3641* the event loop. Invoked with (args...).3642* @param {...*} args... - any number of additional arguments to pass to the3643* callback on the next tick.3644* @example3645*3646* var call_order = [];3647* async.nextTick(function() {3648* call_order.push('two');3649* // call_order now equals ['one','two']3650* });3651* call_order.push('one');3652*3653* async.setImmediate(function (a, b, c) {3654* // a, b, and c equal 1, 2, and 33655* }, 1, 2, 3);3656*/3657var _defer$1;36583659if (hasNextTick) {3660_defer$1 = process.nextTick;3661} else if (hasSetImmediate) {3662_defer$1 = setImmediate;3663} else {3664_defer$1 = fallback;3665}36663667var nextTick = wrap(_defer$1);36683669var parallel = awaitify((eachfn, tasks, callback) => {3670var results = isArrayLike(tasks) ? [] : {};36713672eachfn(tasks, (task, key, taskCb) => {3673wrapAsync(task)((err, ...result) => {3674if (result.length < 2) {3675[result] = result;3676}3677results[key] = result;3678taskCb(err);3679});3680}, err => callback(err, results));3681}, 3);36823683/**3684* Run the `tasks` collection of functions in parallel, without waiting until3685* the previous function has completed. If any of the functions pass an error to3686* its callback, the main `callback` is immediately called with the value of the3687* error. Once the `tasks` have completed, the results are passed to the final3688* `callback` as an array.3689*3690* **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about3691* parallel execution of code. If your tasks do not use any timers or perform3692* any I/O, they will actually be executed in series. Any synchronous setup3693* sections for each task will happen one after the other. JavaScript remains3694* single-threaded.3695*3696* **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the3697* execution of other tasks when a task fails.3698*3699* It is also possible to use an object instead of an array. Each property will3700* be run as a function and the results will be passed to the final `callback`3701* as an object instead of an array. This can be a more readable way of handling3702* results from {@link async.parallel}.3703*3704* @name parallel3705* @static3706* @memberOf module:ControlFlow3707* @method3708* @category Control Flow3709* @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of3710* [async functions]{@link AsyncFunction} to run.3711* Each async function can complete with any number of optional `result` values.3712* @param {Function} [callback] - An optional callback to run once all the3713* functions have completed successfully. This function gets a results array3714* (or object) containing all the result arguments passed to the task callbacks.3715* Invoked with (err, results).3716* @returns {Promise} a promise, if a callback is not passed3717*3718* @example3719*3720* //Using Callbacks3721* async.parallel([3722* function(callback) {3723* setTimeout(function() {3724* callback(null, 'one');3725* }, 200);3726* },3727* function(callback) {3728* setTimeout(function() {3729* callback(null, 'two');3730* }, 100);3731* }3732* ], function(err, results) {3733* console.log(results);3734* // results is equal to ['one','two'] even though3735* // the second function had a shorter timeout.3736* });3737*3738* // an example using an object instead of an array3739* async.parallel({3740* one: function(callback) {3741* setTimeout(function() {3742* callback(null, 1);3743* }, 200);3744* },3745* two: function(callback) {3746* setTimeout(function() {3747* callback(null, 2);3748* }, 100);3749* }3750* }, function(err, results) {3751* console.log(results);3752* // results is equal to: { one: 1, two: 2 }3753* });3754*3755* //Using Promises3756* async.parallel([3757* function(callback) {3758* setTimeout(function() {3759* callback(null, 'one');3760* }, 200);3761* },3762* function(callback) {3763* setTimeout(function() {3764* callback(null, 'two');3765* }, 100);3766* }3767* ]).then(results => {3768* console.log(results);3769* // results is equal to ['one','two'] even though3770* // the second function had a shorter timeout.3771* }).catch(err => {3772* console.log(err);3773* });3774*3775* // an example using an object instead of an array3776* async.parallel({3777* one: function(callback) {3778* setTimeout(function() {3779* callback(null, 1);3780* }, 200);3781* },3782* two: function(callback) {3783* setTimeout(function() {3784* callback(null, 2);3785* }, 100);3786* }3787* }).then(results => {3788* console.log(results);3789* // results is equal to: { one: 1, two: 2 }3790* }).catch(err => {3791* console.log(err);3792* });3793*3794* //Using async/await3795* async () => {3796* try {3797* let results = await async.parallel([3798* function(callback) {3799* setTimeout(function() {3800* callback(null, 'one');3801* }, 200);3802* },3803* function(callback) {3804* setTimeout(function() {3805* callback(null, 'two');3806* }, 100);3807* }3808* ]);3809* console.log(results);3810* // results is equal to ['one','two'] even though3811* // the second function had a shorter timeout.3812* }3813* catch (err) {3814* console.log(err);3815* }3816* }3817*3818* // an example using an object instead of an array3819* async () => {3820* try {3821* let results = await async.parallel({3822* one: function(callback) {3823* setTimeout(function() {3824* callback(null, 1);3825* }, 200);3826* },3827* two: function(callback) {3828* setTimeout(function() {3829* callback(null, 2);3830* }, 100);3831* }3832* });3833* console.log(results);3834* // results is equal to: { one: 1, two: 2 }3835* }3836* catch (err) {3837* console.log(err);3838* }3839* }3840*3841*/3842function parallel$1(tasks, callback) {3843return parallel(eachOf$1, tasks, callback);3844}38453846/**3847* The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a3848* time.3849*3850* @name parallelLimit3851* @static3852* @memberOf module:ControlFlow3853* @method3854* @see [async.parallel]{@link module:ControlFlow.parallel}3855* @category Control Flow3856* @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of3857* [async functions]{@link AsyncFunction} to run.3858* Each async function can complete with any number of optional `result` values.3859* @param {number} limit - The maximum number of async operations at a time.3860* @param {Function} [callback] - An optional callback to run once all the3861* functions have completed successfully. This function gets a results array3862* (or object) containing all the result arguments passed to the task callbacks.3863* Invoked with (err, results).3864* @returns {Promise} a promise, if a callback is not passed3865*/3866function parallelLimit(tasks, limit, callback) {3867return parallel(eachOfLimit(limit), tasks, callback);3868}38693870/**3871* A queue of tasks for the worker function to complete.3872* @typedef {Iterable} QueueObject3873* @memberOf module:ControlFlow3874* @property {Function} length - a function returning the number of items3875* waiting to be processed. Invoke with `queue.length()`.3876* @property {boolean} started - a boolean indicating whether or not any3877* items have been pushed and processed by the queue.3878* @property {Function} running - a function returning the number of items3879* currently being processed. Invoke with `queue.running()`.3880* @property {Function} workersList - a function returning the array of items3881* currently being processed. Invoke with `queue.workersList()`.3882* @property {Function} idle - a function returning false if there are items3883* waiting or being processed, or true if not. Invoke with `queue.idle()`.3884* @property {number} concurrency - an integer for determining how many `worker`3885* functions should be run in parallel. This property can be changed after a3886* `queue` is created to alter the concurrency on-the-fly.3887* @property {number} payload - an integer that specifies how many items are3888* passed to the worker function at a time. only applies if this is a3889* [cargo]{@link module:ControlFlow.cargo} object3890* @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback`3891* once the `worker` has finished processing the task. Instead of a single task,3892* a `tasks` array can be submitted. The respective callback is used for every3893* task in the list. Invoke with `queue.push(task, [callback])`,3894* @property {AsyncFunction} unshift - add a new task to the front of the `queue`.3895* Invoke with `queue.unshift(task, [callback])`.3896* @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns3897* a promise that rejects if an error occurs.3898* @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns3899* a promise that rejects if an error occurs.3900* @property {Function} remove - remove items from the queue that match a test3901* function. The test function will be passed an object with a `data` property,3902* and a `priority` property, if this is a3903* [priorityQueue]{@link module:ControlFlow.priorityQueue} object.3904* Invoked with `queue.remove(testFn)`, where `testFn` is of the form3905* `function ({data, priority}) {}` and returns a Boolean.3906* @property {Function} saturated - a function that sets a callback that is3907* called when the number of running workers hits the `concurrency` limit, and3908* further tasks will be queued. If the callback is omitted, `q.saturated()`3909* returns a promise for the next occurrence.3910* @property {Function} unsaturated - a function that sets a callback that is3911* called when the number of running workers is less than the `concurrency` &3912* `buffer` limits, and further tasks will not be queued. If the callback is3913* omitted, `q.unsaturated()` returns a promise for the next occurrence.3914* @property {number} buffer - A minimum threshold buffer in order to say that3915* the `queue` is `unsaturated`.3916* @property {Function} empty - a function that sets a callback that is called3917* when the last item from the `queue` is given to a `worker`. If the callback3918* is omitted, `q.empty()` returns a promise for the next occurrence.3919* @property {Function} drain - a function that sets a callback that is called3920* when the last item from the `queue` has returned from the `worker`. If the3921* callback is omitted, `q.drain()` returns a promise for the next occurrence.3922* @property {Function} error - a function that sets a callback that is called3923* when a task errors. Has the signature `function(error, task)`. If the3924* callback is omitted, `error()` returns a promise that rejects on the next3925* error.3926* @property {boolean} paused - a boolean for determining whether the queue is3927* in a paused state.3928* @property {Function} pause - a function that pauses the processing of tasks3929* until `resume()` is called. Invoke with `queue.pause()`.3930* @property {Function} resume - a function that resumes the processing of3931* queued tasks when the queue is paused. Invoke with `queue.resume()`.3932* @property {Function} kill - a function that removes the `drain` callback and3933* empties remaining tasks from the queue forcing it to go idle. No more tasks3934* should be pushed to the queue after calling this function. Invoke with `queue.kill()`.3935*3936* @example3937* const q = async.queue(worker, 2)3938* q.push(item1)3939* q.push(item2)3940* q.push(item3)3941* // queues are iterable, spread into an array to inspect3942* const items = [...q] // [item1, item2, item3]3943* // or use for of3944* for (let item of q) {3945* console.log(item)3946* }3947*3948* q.drain(() => {3949* console.log('all done')3950* })3951* // or3952* await q.drain()3953*/39543955/**3956* Creates a `queue` object with the specified `concurrency`. Tasks added to the3957* `queue` are processed in parallel (up to the `concurrency` limit). If all3958* `worker`s are in progress, the task is queued until one becomes available.3959* Once a `worker` completes a `task`, that `task`'s callback is called.3960*3961* @name queue3962* @static3963* @memberOf module:ControlFlow3964* @method3965* @category Control Flow3966* @param {AsyncFunction} worker - An async function for processing a queued task.3967* If you want to handle errors from an individual task, pass a callback to3968* `q.push()`. Invoked with (task, callback).3969* @param {number} [concurrency=1] - An `integer` for determining how many3970* `worker` functions should be run in parallel. If omitted, the concurrency3971* defaults to `1`. If the concurrency is `0`, an error is thrown.3972* @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be3973* attached as certain properties to listen for specific events during the3974* lifecycle of the queue.3975* @example3976*3977* // create a queue object with concurrency 23978* var q = async.queue(function(task, callback) {3979* console.log('hello ' + task.name);3980* callback();3981* }, 2);3982*3983* // assign a callback3984* q.drain(function() {3985* console.log('all items have been processed');3986* });3987* // or await the end3988* await q.drain()3989*3990* // assign an error callback3991* q.error(function(err, task) {3992* console.error('task experienced an error');3993* });3994*3995* // add some items to the queue3996* q.push({name: 'foo'}, function(err) {3997* console.log('finished processing foo');3998* });3999* // callback is optional4000* q.push({name: 'bar'});4001*4002* // add some items to the queue (batch-wise)4003* q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {4004* console.log('finished processing item');4005* });4006*4007* // add some items to the front of the queue4008* q.unshift({name: 'bar'}, function (err) {4009* console.log('finished processing bar');4010* });4011*/4012function queue$1 (worker, concurrency) {4013var _worker = wrapAsync(worker);4014return queue((items, cb) => {4015_worker(items[0], cb);4016}, concurrency, 1);4017}40184019// Binary min-heap implementation used for priority queue.4020// Implementation is stable, i.e. push time is considered for equal priorities4021class Heap {4022constructor() {4023this.heap = [];4024this.pushCount = Number.MIN_SAFE_INTEGER;4025}40264027get length() {4028return this.heap.length;4029}40304031empty () {4032this.heap = [];4033return this;4034}40354036percUp(index) {4037let p;40384039while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) {4040let t = this.heap[index];4041this.heap[index] = this.heap[p];4042this.heap[p] = t;40434044index = p;4045}4046}40474048percDown(index) {4049let l;40504051while ((l=leftChi(index)) < this.heap.length) {4052if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) {4053l = l+1;4054}40554056if (smaller(this.heap[index], this.heap[l])) {4057break;4058}40594060let t = this.heap[index];4061this.heap[index] = this.heap[l];4062this.heap[l] = t;40634064index = l;4065}4066}40674068push(node) {4069node.pushCount = ++this.pushCount;4070this.heap.push(node);4071this.percUp(this.heap.length-1);4072}40734074unshift(node) {4075return this.heap.push(node);4076}40774078shift() {4079let [top] = this.heap;40804081this.heap[0] = this.heap[this.heap.length-1];4082this.heap.pop();4083this.percDown(0);40844085return top;4086}40874088toArray() {4089return [...this];4090}40914092*[Symbol.iterator] () {4093for (let i = 0; i < this.heap.length; i++) {4094yield this.heap[i].data;4095}4096}40974098remove (testFn) {4099let j = 0;4100for (let i = 0; i < this.heap.length; i++) {4101if (!testFn(this.heap[i])) {4102this.heap[j] = this.heap[i];4103j++;4104}4105}41064107this.heap.splice(j);41084109for (let i = parent(this.heap.length-1); i >= 0; i--) {4110this.percDown(i);4111}41124113return this;4114}4115}41164117function leftChi(i) {4118return (i<<1)+1;4119}41204121function parent(i) {4122return ((i+1)>>1)-1;4123}41244125function smaller(x, y) {4126if (x.priority !== y.priority) {4127return x.priority < y.priority;4128}4129else {4130return x.pushCount < y.pushCount;4131}4132}41334134/**4135* The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and4136* completed in ascending priority order.4137*4138* @name priorityQueue4139* @static4140* @memberOf module:ControlFlow4141* @method4142* @see [async.queue]{@link module:ControlFlow.queue}4143* @category Control Flow4144* @param {AsyncFunction} worker - An async function for processing a queued task.4145* If you want to handle errors from an individual task, pass a callback to4146* `q.push()`.4147* Invoked with (task, callback).4148* @param {number} concurrency - An `integer` for determining how many `worker`4149* functions should be run in parallel. If omitted, the concurrency defaults to4150* `1`. If the concurrency is `0`, an error is thrown.4151* @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three4152* differences between `queue` and `priorityQueue` objects:4153* * `push(task, priority, [callback])` - `priority` should be a number. If an4154* array of `tasks` is given, all tasks will be assigned the same priority.4155* * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`,4156* except this returns a promise that rejects if an error occurs.4157* * The `unshift` and `unshiftAsync` methods were removed.4158*/4159function priorityQueue(worker, concurrency) {4160// Start with a normal queue4161var q = queue$1(worker, concurrency);41624163var {4164push,4165pushAsync4166} = q;41674168q._tasks = new Heap();4169q._createTaskItem = ({data, priority}, callback) => {4170return {4171data,4172priority,4173callback4174};4175};41764177function createDataItems(tasks, priority) {4178if (!Array.isArray(tasks)) {4179return {data: tasks, priority};4180}4181return tasks.map(data => { return {data, priority}; });4182}41834184// Override push to accept second parameter representing priority4185q.push = function(data, priority = 0, callback) {4186return push(createDataItems(data, priority), callback);4187};41884189q.pushAsync = function(data, priority = 0, callback) {4190return pushAsync(createDataItems(data, priority), callback);4191};41924193// Remove unshift functions4194delete q.unshift;4195delete q.unshiftAsync;41964197return q;4198}41994200/**4201* Runs the `tasks` array of functions in parallel, without waiting until the4202* previous function has completed. Once any of the `tasks` complete or pass an4203* error to its callback, the main `callback` is immediately called. It's4204* equivalent to `Promise.race()`.4205*4206* @name race4207* @static4208* @memberOf module:ControlFlow4209* @method4210* @category Control Flow4211* @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}4212* to run. Each function can complete with an optional `result` value.4213* @param {Function} callback - A callback to run once any of the functions have4214* completed. This function gets an error or result from the first function that4215* completed. Invoked with (err, result).4216* @returns {Promise} a promise, if a callback is omitted4217* @example4218*4219* async.race([4220* function(callback) {4221* setTimeout(function() {4222* callback(null, 'one');4223* }, 200);4224* },4225* function(callback) {4226* setTimeout(function() {4227* callback(null, 'two');4228* }, 100);4229* }4230* ],4231* // main callback4232* function(err, result) {4233* // the result will be equal to 'two' as it finishes earlier4234* });4235*/4236function race(tasks, callback) {4237callback = once(callback);4238if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));4239if (!tasks.length) return callback();4240for (var i = 0, l = tasks.length; i < l; i++) {4241wrapAsync(tasks[i])(callback);4242}4243}42444245var race$1 = awaitify(race, 2);42464247/**4248* Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.4249*4250* @name reduceRight4251* @static4252* @memberOf module:Collections4253* @method4254* @see [async.reduce]{@link module:Collections.reduce}4255* @alias foldr4256* @category Collection4257* @param {Array} array - A collection to iterate over.4258* @param {*} memo - The initial state of the reduction.4259* @param {AsyncFunction} iteratee - A function applied to each item in the4260* array to produce the next step in the reduction.4261* The `iteratee` should complete with the next state of the reduction.4262* If the iteratee completes with an error, the reduction is stopped and the4263* main `callback` is immediately called with the error.4264* Invoked with (memo, item, callback).4265* @param {Function} [callback] - A callback which is called after all the4266* `iteratee` functions have finished. Result is the reduced value. Invoked with4267* (err, result).4268* @returns {Promise} a promise, if no callback is passed4269*/4270function reduceRight (array, memo, iteratee, callback) {4271var reversed = [...array].reverse();4272return reduce$1(reversed, memo, iteratee, callback);4273}42744275/**4276* Wraps the async function in another function that always completes with a4277* result object, even when it errors.4278*4279* The result object has either the property `error` or `value`.4280*4281* @name reflect4282* @static4283* @memberOf module:Utils4284* @method4285* @category Util4286* @param {AsyncFunction} fn - The async function you want to wrap4287* @returns {Function} - A function that always passes null to it's callback as4288* the error. The second argument to the callback will be an `object` with4289* either an `error` or a `value` property.4290* @example4291*4292* async.parallel([4293* async.reflect(function(callback) {4294* // do some stuff ...4295* callback(null, 'one');4296* }),4297* async.reflect(function(callback) {4298* // do some more stuff but error ...4299* callback('bad stuff happened');4300* }),4301* async.reflect(function(callback) {4302* // do some more stuff ...4303* callback(null, 'two');4304* })4305* ],4306* // optional callback4307* function(err, results) {4308* // values4309* // results[0].value = 'one'4310* // results[1].error = 'bad stuff happened'4311* // results[2].value = 'two'4312* });4313*/4314function reflect(fn) {4315var _fn = wrapAsync(fn);4316return initialParams(function reflectOn(args, reflectCallback) {4317args.push((error, ...cbArgs) => {4318let retVal = {};4319if (error) {4320retVal.error = error;4321}4322if (cbArgs.length > 0){4323var value = cbArgs;4324if (cbArgs.length <= 1) {4325[value] = cbArgs;4326}4327retVal.value = value;4328}4329reflectCallback(null, retVal);4330});43314332return _fn.apply(this, args);4333});4334}43354336/**4337* A helper function that wraps an array or an object of functions with `reflect`.4338*4339* @name reflectAll4340* @static4341* @memberOf module:Utils4342* @method4343* @see [async.reflect]{@link module:Utils.reflect}4344* @category Util4345* @param {Array|Object|Iterable} tasks - The collection of4346* [async functions]{@link AsyncFunction} to wrap in `async.reflect`.4347* @returns {Array} Returns an array of async functions, each wrapped in4348* `async.reflect`4349* @example4350*4351* let tasks = [4352* function(callback) {4353* setTimeout(function() {4354* callback(null, 'one');4355* }, 200);4356* },4357* function(callback) {4358* // do some more stuff but error ...4359* callback(new Error('bad stuff happened'));4360* },4361* function(callback) {4362* setTimeout(function() {4363* callback(null, 'two');4364* }, 100);4365* }4366* ];4367*4368* async.parallel(async.reflectAll(tasks),4369* // optional callback4370* function(err, results) {4371* // values4372* // results[0].value = 'one'4373* // results[1].error = Error('bad stuff happened')4374* // results[2].value = 'two'4375* });4376*4377* // an example using an object instead of an array4378* let tasks = {4379* one: function(callback) {4380* setTimeout(function() {4381* callback(null, 'one');4382* }, 200);4383* },4384* two: function(callback) {4385* callback('two');4386* },4387* three: function(callback) {4388* setTimeout(function() {4389* callback(null, 'three');4390* }, 100);4391* }4392* };4393*4394* async.parallel(async.reflectAll(tasks),4395* // optional callback4396* function(err, results) {4397* // values4398* // results.one.value = 'one'4399* // results.two.error = 'two'4400* // results.three.value = 'three'4401* });4402*/4403function reflectAll(tasks) {4404var results;4405if (Array.isArray(tasks)) {4406results = tasks.map(reflect);4407} else {4408results = {};4409Object.keys(tasks).forEach(key => {4410results[key] = reflect.call(this, tasks[key]);4411});4412}4413return results;4414}44154416function reject(eachfn, arr, _iteratee, callback) {4417const iteratee = wrapAsync(_iteratee);4418return _filter(eachfn, arr, (value, cb) => {4419iteratee(value, (err, v) => {4420cb(err, !v);4421});4422}, callback);4423}44244425/**4426* The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.4427*4428* @name reject4429* @static4430* @memberOf module:Collections4431* @method4432* @see [async.filter]{@link module:Collections.filter}4433* @category Collection4434* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.4435* @param {Function} iteratee - An async truth test to apply to each item in4436* `coll`.4437* The should complete with a boolean value as its `result`.4438* Invoked with (item, callback).4439* @param {Function} [callback] - A callback which is called after all the4440* `iteratee` functions have finished. Invoked with (err, results).4441* @returns {Promise} a promise, if no callback is passed4442* @example4443*4444* // dir1 is a directory that contains file1.txt, file2.txt4445* // dir2 is a directory that contains file3.txt, file4.txt4446* // dir3 is a directory that contains file5.txt4447*4448* const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];4449*4450* // asynchronous function that checks if a file exists4451* function fileExists(file, callback) {4452* fs.access(file, fs.constants.F_OK, (err) => {4453* callback(null, !err);4454* });4455* }4456*4457* // Using callbacks4458* async.reject(fileList, fileExists, function(err, results) {4459* // [ 'dir3/file6.txt' ]4460* // results now equals an array of the non-existing files4461* });4462*4463* // Using Promises4464* async.reject(fileList, fileExists)4465* .then( results => {4466* console.log(results);4467* // [ 'dir3/file6.txt' ]4468* // results now equals an array of the non-existing files4469* }).catch( err => {4470* console.log(err);4471* });4472*4473* // Using async/await4474* async () => {4475* try {4476* let results = await async.reject(fileList, fileExists);4477* console.log(results);4478* // [ 'dir3/file6.txt' ]4479* // results now equals an array of the non-existing files4480* }4481* catch (err) {4482* console.log(err);4483* }4484* }4485*4486*/4487function reject$1 (coll, iteratee, callback) {4488return reject(eachOf$1, coll, iteratee, callback)4489}4490var reject$2 = awaitify(reject$1, 3);44914492/**4493* The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a4494* time.4495*4496* @name rejectLimit4497* @static4498* @memberOf module:Collections4499* @method4500* @see [async.reject]{@link module:Collections.reject}4501* @category Collection4502* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.4503* @param {number} limit - The maximum number of async operations at a time.4504* @param {Function} iteratee - An async truth test to apply to each item in4505* `coll`.4506* The should complete with a boolean value as its `result`.4507* Invoked with (item, callback).4508* @param {Function} [callback] - A callback which is called after all the4509* `iteratee` functions have finished. Invoked with (err, results).4510* @returns {Promise} a promise, if no callback is passed4511*/4512function rejectLimit (coll, limit, iteratee, callback) {4513return reject(eachOfLimit(limit), coll, iteratee, callback)4514}4515var rejectLimit$1 = awaitify(rejectLimit, 4);45164517/**4518* The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.4519*4520* @name rejectSeries4521* @static4522* @memberOf module:Collections4523* @method4524* @see [async.reject]{@link module:Collections.reject}4525* @category Collection4526* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.4527* @param {Function} iteratee - An async truth test to apply to each item in4528* `coll`.4529* The should complete with a boolean value as its `result`.4530* Invoked with (item, callback).4531* @param {Function} [callback] - A callback which is called after all the4532* `iteratee` functions have finished. Invoked with (err, results).4533* @returns {Promise} a promise, if no callback is passed4534*/4535function rejectSeries (coll, iteratee, callback) {4536return reject(eachOfSeries$1, coll, iteratee, callback)4537}4538var rejectSeries$1 = awaitify(rejectSeries, 3);45394540function constant$1(value) {4541return function () {4542return value;4543}4544}45454546/**4547* Attempts to get a successful response from `task` no more than `times` times4548* before returning an error. If the task is successful, the `callback` will be4549* passed the result of the successful task. If all attempts fail, the callback4550* will be passed the error and result (if any) of the final attempt.4551*4552* @name retry4553* @static4554* @memberOf module:ControlFlow4555* @method4556* @category Control Flow4557* @see [async.retryable]{@link module:ControlFlow.retryable}4558* @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an4559* object with `times` and `interval` or a number.4560* * `times` - The number of attempts to make before giving up. The default4561* is `5`.4562* * `interval` - The time to wait between retries, in milliseconds. The4563* default is `0`. The interval may also be specified as a function of the4564* retry count (see example).4565* * `errorFilter` - An optional synchronous function that is invoked on4566* erroneous result. If it returns `true` the retry attempts will continue;4567* if the function returns `false` the retry flow is aborted with the current4568* attempt's error and result being returned to the final callback.4569* Invoked with (err).4570* * If `opts` is a number, the number specifies the number of times to retry,4571* with the default interval of `0`.4572* @param {AsyncFunction} task - An async function to retry.4573* Invoked with (callback).4574* @param {Function} [callback] - An optional callback which is called when the4575* task has succeeded, or after the final failed attempt. It receives the `err`4576* and `result` arguments of the last attempt at completing the `task`. Invoked4577* with (err, results).4578* @returns {Promise} a promise if no callback provided4579*4580* @example4581*4582* // The `retry` function can be used as a stand-alone control flow by passing4583* // a callback, as shown below:4584*4585* // try calling apiMethod 3 times4586* async.retry(3, apiMethod, function(err, result) {4587* // do something with the result4588* });4589*4590* // try calling apiMethod 3 times, waiting 200 ms between each retry4591* async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {4592* // do something with the result4593* });4594*4595* // try calling apiMethod 10 times with exponential backoff4596* // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)4597* async.retry({4598* times: 10,4599* interval: function(retryCount) {4600* return 50 * Math.pow(2, retryCount);4601* }4602* }, apiMethod, function(err, result) {4603* // do something with the result4604* });4605*4606* // try calling apiMethod the default 5 times no delay between each retry4607* async.retry(apiMethod, function(err, result) {4608* // do something with the result4609* });4610*4611* // try calling apiMethod only when error condition satisfies, all other4612* // errors will abort the retry control flow and return to final callback4613* async.retry({4614* errorFilter: function(err) {4615* return err.message === 'Temporary error'; // only retry on a specific error4616* }4617* }, apiMethod, function(err, result) {4618* // do something with the result4619* });4620*4621* // to retry individual methods that are not as reliable within other4622* // control flow functions, use the `retryable` wrapper:4623* async.auto({4624* users: api.getUsers.bind(api),4625* payments: async.retryable(3, api.getPayments.bind(api))4626* }, function(err, results) {4627* // do something with the results4628* });4629*4630*/4631const DEFAULT_TIMES = 5;4632const DEFAULT_INTERVAL = 0;46334634function retry(opts, task, callback) {4635var options = {4636times: DEFAULT_TIMES,4637intervalFunc: constant$1(DEFAULT_INTERVAL)4638};46394640if (arguments.length < 3 && typeof opts === 'function') {4641callback = task || promiseCallback();4642task = opts;4643} else {4644parseTimes(options, opts);4645callback = callback || promiseCallback();4646}46474648if (typeof task !== 'function') {4649throw new Error("Invalid arguments for async.retry");4650}46514652var _task = wrapAsync(task);46534654var attempt = 1;4655function retryAttempt() {4656_task((err, ...args) => {4657if (err === false) return4658if (err && attempt++ < options.times &&4659(typeof options.errorFilter != 'function' ||4660options.errorFilter(err))) {4661setTimeout(retryAttempt, options.intervalFunc(attempt - 1));4662} else {4663callback(err, ...args);4664}4665});4666}46674668retryAttempt();4669return callback[PROMISE_SYMBOL]4670}46714672function parseTimes(acc, t) {4673if (typeof t === 'object') {4674acc.times = +t.times || DEFAULT_TIMES;46754676acc.intervalFunc = typeof t.interval === 'function' ?4677t.interval :4678constant$1(+t.interval || DEFAULT_INTERVAL);46794680acc.errorFilter = t.errorFilter;4681} else if (typeof t === 'number' || typeof t === 'string') {4682acc.times = +t || DEFAULT_TIMES;4683} else {4684throw new Error("Invalid arguments for async.retry");4685}4686}46874688/**4689* A close relative of [`retry`]{@link module:ControlFlow.retry}. This method4690* wraps a task and makes it retryable, rather than immediately calling it4691* with retries.4692*4693* @name retryable4694* @static4695* @memberOf module:ControlFlow4696* @method4697* @see [async.retry]{@link module:ControlFlow.retry}4698* @category Control Flow4699* @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional4700* options, exactly the same as from `retry`, except for a `opts.arity` that4701* is the arity of the `task` function, defaulting to `task.length`4702* @param {AsyncFunction} task - the asynchronous function to wrap.4703* This function will be passed any arguments passed to the returned wrapper.4704* Invoked with (...args, callback).4705* @returns {AsyncFunction} The wrapped function, which when invoked, will4706* retry on an error, based on the parameters specified in `opts`.4707* This function will accept the same parameters as `task`.4708* @example4709*4710* async.auto({4711* dep1: async.retryable(3, getFromFlakyService),4712* process: ["dep1", async.retryable(3, function (results, cb) {4713* maybeProcessData(results.dep1, cb);4714* })]4715* }, callback);4716*/4717function retryable (opts, task) {4718if (!task) {4719task = opts;4720opts = null;4721}4722let arity = (opts && opts.arity) || task.length;4723if (isAsync(task)) {4724arity += 1;4725}4726var _task = wrapAsync(task);4727return initialParams((args, callback) => {4728if (args.length < arity - 1 || callback == null) {4729args.push(callback);4730callback = promiseCallback();4731}4732function taskFn(cb) {4733_task(...args, cb);4734}47354736if (opts) retry(opts, taskFn, callback);4737else retry(taskFn, callback);47384739return callback[PROMISE_SYMBOL]4740});4741}47424743/**4744* Run the functions in the `tasks` collection in series, each one running once4745* the previous function has completed. If any functions in the series pass an4746* error to its callback, no more functions are run, and `callback` is4747* immediately called with the value of the error. Otherwise, `callback`4748* receives an array of results when `tasks` have completed.4749*4750* It is also possible to use an object instead of an array. Each property will4751* be run as a function, and the results will be passed to the final `callback`4752* as an object instead of an array. This can be a more readable way of handling4753* results from {@link async.series}.4754*4755* **Note** that while many implementations preserve the order of object4756* properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)4757* explicitly states that4758*4759* > The mechanics and order of enumerating the properties is not specified.4760*4761* So if you rely on the order in which your series of functions are executed,4762* and want this to work on all platforms, consider using an array.4763*4764* @name series4765* @static4766* @memberOf module:ControlFlow4767* @method4768* @category Control Flow4769* @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing4770* [async functions]{@link AsyncFunction} to run in series.4771* Each function can complete with any number of optional `result` values.4772* @param {Function} [callback] - An optional callback to run once all the4773* functions have completed. This function gets a results array (or object)4774* containing all the result arguments passed to the `task` callbacks. Invoked4775* with (err, result).4776* @return {Promise} a promise, if no callback is passed4777* @example4778*4779* //Using Callbacks4780* async.series([4781* function(callback) {4782* setTimeout(function() {4783* // do some async task4784* callback(null, 'one');4785* }, 200);4786* },4787* function(callback) {4788* setTimeout(function() {4789* // then do another async task4790* callback(null, 'two');4791* }, 100);4792* }4793* ], function(err, results) {4794* console.log(results);4795* // results is equal to ['one','two']4796* });4797*4798* // an example using objects instead of arrays4799* async.series({4800* one: function(callback) {4801* setTimeout(function() {4802* // do some async task4803* callback(null, 1);4804* }, 200);4805* },4806* two: function(callback) {4807* setTimeout(function() {4808* // then do another async task4809* callback(null, 2);4810* }, 100);4811* }4812* }, function(err, results) {4813* console.log(results);4814* // results is equal to: { one: 1, two: 2 }4815* });4816*4817* //Using Promises4818* async.series([4819* function(callback) {4820* setTimeout(function() {4821* callback(null, 'one');4822* }, 200);4823* },4824* function(callback) {4825* setTimeout(function() {4826* callback(null, 'two');4827* }, 100);4828* }4829* ]).then(results => {4830* console.log(results);4831* // results is equal to ['one','two']4832* }).catch(err => {4833* console.log(err);4834* });4835*4836* // an example using an object instead of an array4837* async.series({4838* one: function(callback) {4839* setTimeout(function() {4840* // do some async task4841* callback(null, 1);4842* }, 200);4843* },4844* two: function(callback) {4845* setTimeout(function() {4846* // then do another async task4847* callback(null, 2);4848* }, 100);4849* }4850* }).then(results => {4851* console.log(results);4852* // results is equal to: { one: 1, two: 2 }4853* }).catch(err => {4854* console.log(err);4855* });4856*4857* //Using async/await4858* async () => {4859* try {4860* let results = await async.series([4861* function(callback) {4862* setTimeout(function() {4863* // do some async task4864* callback(null, 'one');4865* }, 200);4866* },4867* function(callback) {4868* setTimeout(function() {4869* // then do another async task4870* callback(null, 'two');4871* }, 100);4872* }4873* ]);4874* console.log(results);4875* // results is equal to ['one','two']4876* }4877* catch (err) {4878* console.log(err);4879* }4880* }4881*4882* // an example using an object instead of an array4883* async () => {4884* try {4885* let results = await async.parallel({4886* one: function(callback) {4887* setTimeout(function() {4888* // do some async task4889* callback(null, 1);4890* }, 200);4891* },4892* two: function(callback) {4893* setTimeout(function() {4894* // then do another async task4895* callback(null, 2);4896* }, 100);4897* }4898* });4899* console.log(results);4900* // results is equal to: { one: 1, two: 2 }4901* }4902* catch (err) {4903* console.log(err);4904* }4905* }4906*4907*/4908function series(tasks, callback) {4909return parallel(eachOfSeries$1, tasks, callback);4910}49114912/**4913* Returns `true` if at least one element in the `coll` satisfies an async test.4914* If any iteratee call returns `true`, the main `callback` is immediately4915* called.4916*4917* @name some4918* @static4919* @memberOf module:Collections4920* @method4921* @alias any4922* @category Collection4923* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.4924* @param {AsyncFunction} iteratee - An async truth test to apply to each item4925* in the collections in parallel.4926* The iteratee should complete with a boolean `result` value.4927* Invoked with (item, callback).4928* @param {Function} [callback] - A callback which is called as soon as any4929* iteratee returns `true`, or after all the iteratee functions have finished.4930* Result will be either `true` or `false` depending on the values of the async4931* tests. Invoked with (err, result).4932* @returns {Promise} a promise, if no callback provided4933* @example4934*4935* // dir1 is a directory that contains file1.txt, file2.txt4936* // dir2 is a directory that contains file3.txt, file4.txt4937* // dir3 is a directory that contains file5.txt4938* // dir4 does not exist4939*4940* // asynchronous function that checks if a file exists4941* function fileExists(file, callback) {4942* fs.access(file, fs.constants.F_OK, (err) => {4943* callback(null, !err);4944* });4945* }4946*4947* // Using callbacks4948* async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,4949* function(err, result) {4950* console.log(result);4951* // true4952* // result is true since some file in the list exists4953* }4954*);4955*4956* async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,4957* function(err, result) {4958* console.log(result);4959* // false4960* // result is false since none of the files exists4961* }4962*);4963*4964* // Using Promises4965* async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)4966* .then( result => {4967* console.log(result);4968* // true4969* // result is true since some file in the list exists4970* }).catch( err => {4971* console.log(err);4972* });4973*4974* async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)4975* .then( result => {4976* console.log(result);4977* // false4978* // result is false since none of the files exists4979* }).catch( err => {4980* console.log(err);4981* });4982*4983* // Using async/await4984* async () => {4985* try {4986* let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);4987* console.log(result);4988* // true4989* // result is true since some file in the list exists4990* }4991* catch (err) {4992* console.log(err);4993* }4994* }4995*4996* async () => {4997* try {4998* let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);4999* console.log(result);5000* // false5001* // result is false since none of the files exists5002* }5003* catch (err) {5004* console.log(err);5005* }5006* }5007*5008*/5009function some(coll, iteratee, callback) {5010return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback)5011}5012var some$1 = awaitify(some, 3);50135014/**5015* The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.5016*5017* @name someLimit5018* @static5019* @memberOf module:Collections5020* @method5021* @see [async.some]{@link module:Collections.some}5022* @alias anyLimit5023* @category Collection5024* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.5025* @param {number} limit - The maximum number of async operations at a time.5026* @param {AsyncFunction} iteratee - An async truth test to apply to each item5027* in the collections in parallel.5028* The iteratee should complete with a boolean `result` value.5029* Invoked with (item, callback).5030* @param {Function} [callback] - A callback which is called as soon as any5031* iteratee returns `true`, or after all the iteratee functions have finished.5032* Result will be either `true` or `false` depending on the values of the async5033* tests. Invoked with (err, result).5034* @returns {Promise} a promise, if no callback provided5035*/5036function someLimit(coll, limit, iteratee, callback) {5037return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback)5038}5039var someLimit$1 = awaitify(someLimit, 4);50405041/**5042* The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.5043*5044* @name someSeries5045* @static5046* @memberOf module:Collections5047* @method5048* @see [async.some]{@link module:Collections.some}5049* @alias anySeries5050* @category Collection5051* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.5052* @param {AsyncFunction} iteratee - An async truth test to apply to each item5053* in the collections in series.5054* The iteratee should complete with a boolean `result` value.5055* Invoked with (item, callback).5056* @param {Function} [callback] - A callback which is called as soon as any5057* iteratee returns `true`, or after all the iteratee functions have finished.5058* Result will be either `true` or `false` depending on the values of the async5059* tests. Invoked with (err, result).5060* @returns {Promise} a promise, if no callback provided5061*/5062function someSeries(coll, iteratee, callback) {5063return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback)5064}5065var someSeries$1 = awaitify(someSeries, 3);50665067/**5068* Sorts a list by the results of running each `coll` value through an async5069* `iteratee`.5070*5071* @name sortBy5072* @static5073* @memberOf module:Collections5074* @method5075* @category Collection5076* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.5077* @param {AsyncFunction} iteratee - An async function to apply to each item in5078* `coll`.5079* The iteratee should complete with a value to use as the sort criteria as5080* its `result`.5081* Invoked with (item, callback).5082* @param {Function} callback - A callback which is called after all the5083* `iteratee` functions have finished, or an error occurs. Results is the items5084* from the original `coll` sorted by the values returned by the `iteratee`5085* calls. Invoked with (err, results).5086* @returns {Promise} a promise, if no callback passed5087* @example5088*5089* // bigfile.txt is a file that is 251100 bytes in size5090* // mediumfile.txt is a file that is 11000 bytes in size5091* // smallfile.txt is a file that is 121 bytes in size5092*5093* // asynchronous function that returns the file size in bytes5094* function getFileSizeInBytes(file, callback) {5095* fs.stat(file, function(err, stat) {5096* if (err) {5097* return callback(err);5098* }5099* callback(null, stat.size);5100* });5101* }5102*5103* // Using callbacks5104* async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes,5105* function(err, results) {5106* if (err) {5107* console.log(err);5108* } else {5109* console.log(results);5110* // results is now the original array of files sorted by5111* // file size (ascending by default), e.g.5112* // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']5113* }5114* }5115* );5116*5117* // By modifying the callback parameter the5118* // sorting order can be influenced:5119*5120* // ascending order5121* async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) {5122* getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {5123* if (getFileSizeErr) return callback(getFileSizeErr);5124* callback(null, fileSize);5125* });5126* }, function(err, results) {5127* if (err) {5128* console.log(err);5129* } else {5130* console.log(results);5131* // results is now the original array of files sorted by5132* // file size (ascending by default), e.g.5133* // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']5134* }5135* }5136* );5137*5138* // descending order5139* async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) {5140* getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {5141* if (getFileSizeErr) {5142* return callback(getFileSizeErr);5143* }5144* callback(null, fileSize * -1);5145* });5146* }, function(err, results) {5147* if (err) {5148* console.log(err);5149* } else {5150* console.log(results);5151* // results is now the original array of files sorted by5152* // file size (ascending by default), e.g.5153* // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt']5154* }5155* }5156* );5157*5158* // Error handling5159* async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes,5160* function(err, results) {5161* if (err) {5162* console.log(err);5163* // [ Error: ENOENT: no such file or directory ]5164* } else {5165* console.log(results);5166* }5167* }5168* );5169*5170* // Using Promises5171* async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes)5172* .then( results => {5173* console.log(results);5174* // results is now the original array of files sorted by5175* // file size (ascending by default), e.g.5176* // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']5177* }).catch( err => {5178* console.log(err);5179* });5180*5181* // Error handling5182* async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes)5183* .then( results => {5184* console.log(results);5185* }).catch( err => {5186* console.log(err);5187* // [ Error: ENOENT: no such file or directory ]5188* });5189*5190* // Using async/await5191* (async () => {5192* try {5193* let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);5194* console.log(results);5195* // results is now the original array of files sorted by5196* // file size (ascending by default), e.g.5197* // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']5198* }5199* catch (err) {5200* console.log(err);5201* }5202* })();5203*5204* // Error handling5205* async () => {5206* try {5207* let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);5208* console.log(results);5209* }5210* catch (err) {5211* console.log(err);5212* // [ Error: ENOENT: no such file or directory ]5213* }5214* }5215*5216*/5217function sortBy (coll, iteratee, callback) {5218var _iteratee = wrapAsync(iteratee);5219return map$1(coll, (x, iterCb) => {5220_iteratee(x, (err, criteria) => {5221if (err) return iterCb(err);5222iterCb(err, {value: x, criteria});5223});5224}, (err, results) => {5225if (err) return callback(err);5226callback(null, results.sort(comparator).map(v => v.value));5227});52285229function comparator(left, right) {5230var a = left.criteria, b = right.criteria;5231return a < b ? -1 : a > b ? 1 : 0;5232}5233}5234var sortBy$1 = awaitify(sortBy, 3);52355236/**5237* Sets a time limit on an asynchronous function. If the function does not call5238* its callback within the specified milliseconds, it will be called with a5239* timeout error. The code property for the error object will be `'ETIMEDOUT'`.5240*5241* @name timeout5242* @static5243* @memberOf module:Utils5244* @method5245* @category Util5246* @param {AsyncFunction} asyncFn - The async function to limit in time.5247* @param {number} milliseconds - The specified time limit.5248* @param {*} [info] - Any variable you want attached (`string`, `object`, etc)5249* to timeout Error for more information..5250* @returns {AsyncFunction} Returns a wrapped function that can be used with any5251* of the control flow functions.5252* Invoke this function with the same parameters as you would `asyncFunc`.5253* @example5254*5255* function myFunction(foo, callback) {5256* doAsyncTask(foo, function(err, data) {5257* // handle errors5258* if (err) return callback(err);5259*5260* // do some stuff ...5261*5262* // return processed data5263* return callback(null, data);5264* });5265* }5266*5267* var wrapped = async.timeout(myFunction, 1000);5268*5269* // call `wrapped` as you would `myFunction`5270* wrapped({ bar: 'bar' }, function(err, data) {5271* // if `myFunction` takes < 1000 ms to execute, `err`5272* // and `data` will have their expected values5273*5274* // else `err` will be an Error with the code 'ETIMEDOUT'5275* });5276*/5277function timeout(asyncFn, milliseconds, info) {5278var fn = wrapAsync(asyncFn);52795280return initialParams((args, callback) => {5281var timedOut = false;5282var timer;52835284function timeoutCallback() {5285var name = asyncFn.name || 'anonymous';5286var error = new Error('Callback function "' + name + '" timed out.');5287error.code = 'ETIMEDOUT';5288if (info) {5289error.info = info;5290}5291timedOut = true;5292callback(error);5293}52945295args.push((...cbArgs) => {5296if (!timedOut) {5297callback(...cbArgs);5298clearTimeout(timer);5299}5300});53015302// setup timer and call original function5303timer = setTimeout(timeoutCallback, milliseconds);5304fn(...args);5305});5306}53075308function range(size) {5309var result = Array(size);5310while (size--) {5311result[size] = size;5312}5313return result;5314}53155316/**5317* The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a5318* time.5319*5320* @name timesLimit5321* @static5322* @memberOf module:ControlFlow5323* @method5324* @see [async.times]{@link module:ControlFlow.times}5325* @category Control Flow5326* @param {number} count - The number of times to run the function.5327* @param {number} limit - The maximum number of async operations at a time.5328* @param {AsyncFunction} iteratee - The async function to call `n` times.5329* Invoked with the iteration index and a callback: (n, next).5330* @param {Function} callback - see [async.map]{@link module:Collections.map}.5331* @returns {Promise} a promise, if no callback is provided5332*/5333function timesLimit(count, limit, iteratee, callback) {5334var _iteratee = wrapAsync(iteratee);5335return mapLimit$1(range(count), limit, _iteratee, callback);5336}53375338/**5339* Calls the `iteratee` function `n` times, and accumulates results in the same5340* manner you would use with [map]{@link module:Collections.map}.5341*5342* @name times5343* @static5344* @memberOf module:ControlFlow5345* @method5346* @see [async.map]{@link module:Collections.map}5347* @category Control Flow5348* @param {number} n - The number of times to run the function.5349* @param {AsyncFunction} iteratee - The async function to call `n` times.5350* Invoked with the iteration index and a callback: (n, next).5351* @param {Function} callback - see {@link module:Collections.map}.5352* @returns {Promise} a promise, if no callback is provided5353* @example5354*5355* // Pretend this is some complicated async factory5356* var createUser = function(id, callback) {5357* callback(null, {5358* id: 'user' + id5359* });5360* };5361*5362* // generate 5 users5363* async.times(5, function(n, next) {5364* createUser(n, function(err, user) {5365* next(err, user);5366* });5367* }, function(err, users) {5368* // we should now have 5 users5369* });5370*/5371function times (n, iteratee, callback) {5372return timesLimit(n, Infinity, iteratee, callback)5373}53745375/**5376* The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.5377*5378* @name timesSeries5379* @static5380* @memberOf module:ControlFlow5381* @method5382* @see [async.times]{@link module:ControlFlow.times}5383* @category Control Flow5384* @param {number} n - The number of times to run the function.5385* @param {AsyncFunction} iteratee - The async function to call `n` times.5386* Invoked with the iteration index and a callback: (n, next).5387* @param {Function} callback - see {@link module:Collections.map}.5388* @returns {Promise} a promise, if no callback is provided5389*/5390function timesSeries (n, iteratee, callback) {5391return timesLimit(n, 1, iteratee, callback)5392}53935394/**5395* A relative of `reduce`. Takes an Object or Array, and iterates over each5396* element in parallel, each step potentially mutating an `accumulator` value.5397* The type of the accumulator defaults to the type of collection passed in.5398*5399* @name transform5400* @static5401* @memberOf module:Collections5402* @method5403* @category Collection5404* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.5405* @param {*} [accumulator] - The initial state of the transform. If omitted,5406* it will default to an empty Object or Array, depending on the type of `coll`5407* @param {AsyncFunction} iteratee - A function applied to each item in the5408* collection that potentially modifies the accumulator.5409* Invoked with (accumulator, item, key, callback).5410* @param {Function} [callback] - A callback which is called after all the5411* `iteratee` functions have finished. Result is the transformed accumulator.5412* Invoked with (err, result).5413* @returns {Promise} a promise, if no callback provided5414* @example5415*5416* // file1.txt is a file that is 1000 bytes in size5417* // file2.txt is a file that is 2000 bytes in size5418* // file3.txt is a file that is 3000 bytes in size5419*5420* // helper function that returns human-readable size format from bytes5421* function formatBytes(bytes, decimals = 2) {5422* // implementation not included for brevity5423* return humanReadbleFilesize;5424* }5425*5426* const fileList = ['file1.txt','file2.txt','file3.txt'];5427*5428* // asynchronous function that returns the file size, transformed to human-readable format5429* // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.5430* function transformFileSize(acc, value, key, callback) {5431* fs.stat(value, function(err, stat) {5432* if (err) {5433* return callback(err);5434* }5435* acc[key] = formatBytes(stat.size);5436* callback(null);5437* });5438* }5439*5440* // Using callbacks5441* async.transform(fileList, transformFileSize, function(err, result) {5442* if(err) {5443* console.log(err);5444* } else {5445* console.log(result);5446* // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]5447* }5448* });5449*5450* // Using Promises5451* async.transform(fileList, transformFileSize)5452* .then(result => {5453* console.log(result);5454* // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]5455* }).catch(err => {5456* console.log(err);5457* });5458*5459* // Using async/await5460* (async () => {5461* try {5462* let result = await async.transform(fileList, transformFileSize);5463* console.log(result);5464* // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]5465* }5466* catch (err) {5467* console.log(err);5468* }5469* })();5470*5471* @example5472*5473* // file1.txt is a file that is 1000 bytes in size5474* // file2.txt is a file that is 2000 bytes in size5475* // file3.txt is a file that is 3000 bytes in size5476*5477* // helper function that returns human-readable size format from bytes5478* function formatBytes(bytes, decimals = 2) {5479* // implementation not included for brevity5480* return humanReadbleFilesize;5481* }5482*5483* const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' };5484*5485* // asynchronous function that returns the file size, transformed to human-readable format5486* // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.5487* function transformFileSize(acc, value, key, callback) {5488* fs.stat(value, function(err, stat) {5489* if (err) {5490* return callback(err);5491* }5492* acc[key] = formatBytes(stat.size);5493* callback(null);5494* });5495* }5496*5497* // Using callbacks5498* async.transform(fileMap, transformFileSize, function(err, result) {5499* if(err) {5500* console.log(err);5501* } else {5502* console.log(result);5503* // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }5504* }5505* });5506*5507* // Using Promises5508* async.transform(fileMap, transformFileSize)5509* .then(result => {5510* console.log(result);5511* // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }5512* }).catch(err => {5513* console.log(err);5514* });5515*5516* // Using async/await5517* async () => {5518* try {5519* let result = await async.transform(fileMap, transformFileSize);5520* console.log(result);5521* // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }5522* }5523* catch (err) {5524* console.log(err);5525* }5526* }5527*5528*/5529function transform (coll, accumulator, iteratee, callback) {5530if (arguments.length <= 3 && typeof accumulator === 'function') {5531callback = iteratee;5532iteratee = accumulator;5533accumulator = Array.isArray(coll) ? [] : {};5534}5535callback = once(callback || promiseCallback());5536var _iteratee = wrapAsync(iteratee);55375538eachOf$1(coll, (v, k, cb) => {5539_iteratee(accumulator, v, k, cb);5540}, err => callback(err, accumulator));5541return callback[PROMISE_SYMBOL]5542}55435544/**5545* It runs each task in series but stops whenever any of the functions were5546* successful. If one of the tasks were successful, the `callback` will be5547* passed the result of the successful task. If all tasks fail, the callback5548* will be passed the error and result (if any) of the final attempt.5549*5550* @name tryEach5551* @static5552* @memberOf module:ControlFlow5553* @method5554* @category Control Flow5555* @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to5556* run, each function is passed a `callback(err, result)` it must call on5557* completion with an error `err` (which can be `null`) and an optional `result`5558* value.5559* @param {Function} [callback] - An optional callback which is called when one5560* of the tasks has succeeded, or all have failed. It receives the `err` and5561* `result` arguments of the last attempt at completing the `task`. Invoked with5562* (err, results).5563* @returns {Promise} a promise, if no callback is passed5564* @example5565* async.tryEach([5566* function getDataFromFirstWebsite(callback) {5567* // Try getting the data from the first website5568* callback(err, data);5569* },5570* function getDataFromSecondWebsite(callback) {5571* // First website failed,5572* // Try getting the data from the backup website5573* callback(err, data);5574* }5575* ],5576* // optional callback5577* function(err, results) {5578* Now do something with the data.5579* });5580*5581*/5582function tryEach(tasks, callback) {5583var error = null;5584var result;5585return eachSeries$1(tasks, (task, taskCb) => {5586wrapAsync(task)((err, ...args) => {5587if (err === false) return taskCb(err);55885589if (args.length < 2) {5590[result] = args;5591} else {5592result = args;5593}5594error = err;5595taskCb(err ? null : {});5596});5597}, () => callback(error, result));5598}55995600var tryEach$1 = awaitify(tryEach);56015602/**5603* Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,5604* unmemoized form. Handy for testing.5605*5606* @name unmemoize5607* @static5608* @memberOf module:Utils5609* @method5610* @see [async.memoize]{@link module:Utils.memoize}5611* @category Util5612* @param {AsyncFunction} fn - the memoized function5613* @returns {AsyncFunction} a function that calls the original unmemoized function5614*/5615function unmemoize(fn) {5616return (...args) => {5617return (fn.unmemoized || fn)(...args);5618};5619}56205621/**5622* Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when5623* stopped, or an error occurs.5624*5625* @name whilst5626* @static5627* @memberOf module:ControlFlow5628* @method5629* @category Control Flow5630* @param {AsyncFunction} test - asynchronous truth test to perform before each5631* execution of `iteratee`. Invoked with ().5632* @param {AsyncFunction} iteratee - An async function which is called each time5633* `test` passes. Invoked with (callback).5634* @param {Function} [callback] - A callback which is called after the test5635* function has failed and repeated execution of `iteratee` has stopped. `callback`5636* will be passed an error and any arguments passed to the final `iteratee`'s5637* callback. Invoked with (err, [results]);5638* @returns {Promise} a promise, if no callback is passed5639* @example5640*5641* var count = 0;5642* async.whilst(5643* function test(cb) { cb(null, count < 5); },5644* function iter(callback) {5645* count++;5646* setTimeout(function() {5647* callback(null, count);5648* }, 1000);5649* },5650* function (err, n) {5651* // 5 seconds have passed, n = 55652* }5653* );5654*/5655function whilst(test, iteratee, callback) {5656callback = onlyOnce(callback);5657var _fn = wrapAsync(iteratee);5658var _test = wrapAsync(test);5659var results = [];56605661function next(err, ...rest) {5662if (err) return callback(err);5663results = rest;5664if (err === false) return;5665_test(check);5666}56675668function check(err, truth) {5669if (err) return callback(err);5670if (err === false) return;5671if (!truth) return callback(null, ...results);5672_fn(next);5673}56745675return _test(check);5676}5677var whilst$1 = awaitify(whilst, 3);56785679/**5680* Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when5681* stopped, or an error occurs. `callback` will be passed an error and any5682* arguments passed to the final `iteratee`'s callback.5683*5684* The inverse of [whilst]{@link module:ControlFlow.whilst}.5685*5686* @name until5687* @static5688* @memberOf module:ControlFlow5689* @method5690* @see [async.whilst]{@link module:ControlFlow.whilst}5691* @category Control Flow5692* @param {AsyncFunction} test - asynchronous truth test to perform before each5693* execution of `iteratee`. Invoked with (callback).5694* @param {AsyncFunction} iteratee - An async function which is called each time5695* `test` fails. Invoked with (callback).5696* @param {Function} [callback] - A callback which is called after the test5697* function has passed and repeated execution of `iteratee` has stopped. `callback`5698* will be passed an error and any arguments passed to the final `iteratee`'s5699* callback. Invoked with (err, [results]);5700* @returns {Promise} a promise, if a callback is not passed5701*5702* @example5703* const results = []5704* let finished = false5705* async.until(function test(cb) {5706* cb(null, finished)5707* }, function iter(next) {5708* fetchPage(url, (err, body) => {5709* if (err) return next(err)5710* results = results.concat(body.objects)5711* finished = !!body.next5712* next(err)5713* })5714* }, function done (err) {5715* // all pages have been fetched5716* })5717*/5718function until(test, iteratee, callback) {5719const _test = wrapAsync(test);5720return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback);5721}57225723/**5724* Runs the `tasks` array of functions in series, each passing their results to5725* the next in the array. However, if any of the `tasks` pass an error to their5726* own callback, the next function is not executed, and the main `callback` is5727* immediately called with the error.5728*5729* @name waterfall5730* @static5731* @memberOf module:ControlFlow5732* @method5733* @category Control Flow5734* @param {Array} tasks - An array of [async functions]{@link AsyncFunction}5735* to run.5736* Each function should complete with any number of `result` values.5737* The `result` values will be passed as arguments, in order, to the next task.5738* @param {Function} [callback] - An optional callback to run once all the5739* functions have completed. This will be passed the results of the last task's5740* callback. Invoked with (err, [results]).5741* @returns {Promise} a promise, if a callback is omitted5742* @example5743*5744* async.waterfall([5745* function(callback) {5746* callback(null, 'one', 'two');5747* },5748* function(arg1, arg2, callback) {5749* // arg1 now equals 'one' and arg2 now equals 'two'5750* callback(null, 'three');5751* },5752* function(arg1, callback) {5753* // arg1 now equals 'three'5754* callback(null, 'done');5755* }5756* ], function (err, result) {5757* // result now equals 'done'5758* });5759*5760* // Or, with named functions:5761* async.waterfall([5762* myFirstFunction,5763* mySecondFunction,5764* myLastFunction,5765* ], function (err, result) {5766* // result now equals 'done'5767* });5768* function myFirstFunction(callback) {5769* callback(null, 'one', 'two');5770* }5771* function mySecondFunction(arg1, arg2, callback) {5772* // arg1 now equals 'one' and arg2 now equals 'two'5773* callback(null, 'three');5774* }5775* function myLastFunction(arg1, callback) {5776* // arg1 now equals 'three'5777* callback(null, 'done');5778* }5779*/5780function waterfall (tasks, callback) {5781callback = once(callback);5782if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));5783if (!tasks.length) return callback();5784var taskIndex = 0;57855786function nextTask(args) {5787var task = wrapAsync(tasks[taskIndex++]);5788task(...args, onlyOnce(next));5789}57905791function next(err, ...args) {5792if (err === false) return5793if (err || taskIndex === tasks.length) {5794return callback(err, ...args);5795}5796nextTask(args);5797}57985799nextTask([]);5800}58015802var waterfall$1 = awaitify(waterfall);58035804/**5805* An "async function" in the context of Async is an asynchronous function with5806* a variable number of parameters, with the final parameter being a callback.5807* (`function (arg1, arg2, ..., callback) {}`)5808* The final callback is of the form `callback(err, results...)`, which must be5809* called once the function is completed. The callback should be called with a5810* Error as its first argument to signal that an error occurred.5811* Otherwise, if no error occurred, it should be called with `null` as the first5812* argument, and any additional `result` arguments that may apply, to signal5813* successful completion.5814* The callback must be called exactly once, ideally on a later tick of the5815* JavaScript event loop.5816*5817* This type of function is also referred to as a "Node-style async function",5818* or a "continuation passing-style function" (CPS). Most of the methods of this5819* library are themselves CPS/Node-style async functions, or functions that5820* return CPS/Node-style async functions.5821*5822* Wherever we accept a Node-style async function, we also directly accept an5823* [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.5824* In this case, the `async` function will not be passed a final callback5825* argument, and any thrown error will be used as the `err` argument of the5826* implicit callback, and the return value will be used as the `result` value.5827* (i.e. a `rejected` of the returned Promise becomes the `err` callback5828* argument, and a `resolved` value becomes the `result`.)5829*5830* Note, due to JavaScript limitations, we can only detect native `async`5831* functions and not transpilied implementations.5832* Your environment must have `async`/`await` support for this to work.5833* (e.g. Node > v7.6, or a recent version of a modern browser).5834* If you are using `async` functions through a transpiler (e.g. Babel), you5835* must still wrap the function with [asyncify]{@link module:Utils.asyncify},5836* because the `async function` will be compiled to an ordinary function that5837* returns a promise.5838*5839* @typedef {Function} AsyncFunction5840* @static5841*/58425843var index = {5844apply,5845applyEach: applyEach$1,5846applyEachSeries,5847asyncify,5848auto,5849autoInject,5850cargo,5851cargoQueue: cargo$1,5852compose,5853concat: concat$1,5854concatLimit: concatLimit$1,5855concatSeries: concatSeries$1,5856constant,5857detect: detect$1,5858detectLimit: detectLimit$1,5859detectSeries: detectSeries$1,5860dir,5861doUntil,5862doWhilst: doWhilst$1,5863each,5864eachLimit: eachLimit$2,5865eachOf: eachOf$1,5866eachOfLimit: eachOfLimit$2,5867eachOfSeries: eachOfSeries$1,5868eachSeries: eachSeries$1,5869ensureAsync,5870every: every$1,5871everyLimit: everyLimit$1,5872everySeries: everySeries$1,5873filter: filter$1,5874filterLimit: filterLimit$1,5875filterSeries: filterSeries$1,5876forever: forever$1,5877groupBy,5878groupByLimit: groupByLimit$1,5879groupBySeries,5880log,5881map: map$1,5882mapLimit: mapLimit$1,5883mapSeries: mapSeries$1,5884mapValues,5885mapValuesLimit: mapValuesLimit$1,5886mapValuesSeries,5887memoize,5888nextTick,5889parallel: parallel$1,5890parallelLimit,5891priorityQueue,5892queue: queue$1,5893race: race$1,5894reduce: reduce$1,5895reduceRight,5896reflect,5897reflectAll,5898reject: reject$2,5899rejectLimit: rejectLimit$1,5900rejectSeries: rejectSeries$1,5901retry,5902retryable,5903seq,5904series,5905setImmediate: setImmediate$1,5906some: some$1,5907someLimit: someLimit$1,5908someSeries: someSeries$1,5909sortBy: sortBy$1,5910timeout,5911times,5912timesLimit,5913timesSeries,5914transform,5915tryEach: tryEach$1,5916unmemoize,5917until,5918waterfall: waterfall$1,5919whilst: whilst$1,59205921// aliases5922all: every$1,5923allLimit: everyLimit$1,5924allSeries: everySeries$1,5925any: some$1,5926anyLimit: someLimit$1,5927anySeries: someSeries$1,5928find: detect$1,5929findLimit: detectLimit$1,5930findSeries: detectSeries$1,5931flatMap: concat$1,5932flatMapLimit: concatLimit$1,5933flatMapSeries: concatSeries$1,5934forEach: each,5935forEachSeries: eachSeries$1,5936forEachLimit: eachLimit$2,5937forEachOf: eachOf$1,5938forEachOfSeries: eachOfSeries$1,5939forEachOfLimit: eachOfLimit$2,5940inject: reduce$1,5941foldl: reduce$1,5942foldr: reduceRight,5943select: filter$1,5944selectLimit: filterLimit$1,5945selectSeries: filterSeries$1,5946wrapSync: asyncify,5947during: whilst$1,5948doDuring: doWhilst$15949};59505951exports.default = index;5952exports.apply = apply;5953exports.applyEach = applyEach$1;5954exports.applyEachSeries = applyEachSeries;5955exports.asyncify = asyncify;5956exports.auto = auto;5957exports.autoInject = autoInject;5958exports.cargo = cargo;5959exports.cargoQueue = cargo$1;5960exports.compose = compose;5961exports.concat = concat$1;5962exports.concatLimit = concatLimit$1;5963exports.concatSeries = concatSeries$1;5964exports.constant = constant;5965exports.detect = detect$1;5966exports.detectLimit = detectLimit$1;5967exports.detectSeries = detectSeries$1;5968exports.dir = dir;5969exports.doUntil = doUntil;5970exports.doWhilst = doWhilst$1;5971exports.each = each;5972exports.eachLimit = eachLimit$2;5973exports.eachOf = eachOf$1;5974exports.eachOfLimit = eachOfLimit$2;5975exports.eachOfSeries = eachOfSeries$1;5976exports.eachSeries = eachSeries$1;5977exports.ensureAsync = ensureAsync;5978exports.every = every$1;5979exports.everyLimit = everyLimit$1;5980exports.everySeries = everySeries$1;5981exports.filter = filter$1;5982exports.filterLimit = filterLimit$1;5983exports.filterSeries = filterSeries$1;5984exports.forever = forever$1;5985exports.groupBy = groupBy;5986exports.groupByLimit = groupByLimit$1;5987exports.groupBySeries = groupBySeries;5988exports.log = log;5989exports.map = map$1;5990exports.mapLimit = mapLimit$1;5991exports.mapSeries = mapSeries$1;5992exports.mapValues = mapValues;5993exports.mapValuesLimit = mapValuesLimit$1;5994exports.mapValuesSeries = mapValuesSeries;5995exports.memoize = memoize;5996exports.nextTick = nextTick;5997exports.parallel = parallel$1;5998exports.parallelLimit = parallelLimit;5999exports.priorityQueue = priorityQueue;6000exports.queue = queue$1;6001exports.race = race$1;6002exports.reduce = reduce$1;6003exports.reduceRight = reduceRight;6004exports.reflect = reflect;6005exports.reflectAll = reflectAll;6006exports.reject = reject$2;6007exports.rejectLimit = rejectLimit$1;6008exports.rejectSeries = rejectSeries$1;6009exports.retry = retry;6010exports.retryable = retryable;6011exports.seq = seq;6012exports.series = series;6013exports.setImmediate = setImmediate$1;6014exports.some = some$1;6015exports.someLimit = someLimit$1;6016exports.someSeries = someSeries$1;6017exports.sortBy = sortBy$1;6018exports.timeout = timeout;6019exports.times = times;6020exports.timesLimit = timesLimit;6021exports.timesSeries = timesSeries;6022exports.transform = transform;6023exports.tryEach = tryEach$1;6024exports.unmemoize = unmemoize;6025exports.until = until;6026exports.waterfall = waterfall$1;6027exports.whilst = whilst$1;6028exports.all = every$1;6029exports.allLimit = everyLimit$1;6030exports.allSeries = everySeries$1;6031exports.any = some$1;6032exports.anyLimit = someLimit$1;6033exports.anySeries = someSeries$1;6034exports.find = detect$1;6035exports.findLimit = detectLimit$1;6036exports.findSeries = detectSeries$1;6037exports.flatMap = concat$1;6038exports.flatMapLimit = concatLimit$1;6039exports.flatMapSeries = concatSeries$1;6040exports.forEach = each;6041exports.forEachSeries = eachSeries$1;6042exports.forEachLimit = eachLimit$2;6043exports.forEachOf = eachOf$1;6044exports.forEachOfSeries = eachOfSeries$1;6045exports.forEachOfLimit = eachOfLimit$2;6046exports.inject = reduce$1;6047exports.foldl = reduce$1;6048exports.foldr = reduceRight;6049exports.select = filter$1;6050exports.selectLimit = filterLimit$1;6051exports.selectSeries = filterSeries$1;6052exports.wrapSync = asyncify;6053exports.during = whilst$1;6054exports.doDuring = doWhilst$1;60556056Object.defineProperty(exports, '__esModule', { value: true });60576058})));605960606061