async.js 175 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.async = {})));
  5. }(this, (function (exports) { 'use strict';
  6. /**
  7. * Creates a continuation function with some arguments already applied.
  8. *
  9. * Useful as a shorthand when combined with other control flow functions. Any
  10. * arguments passed to the returned function are added to the arguments
  11. * originally passed to apply.
  12. *
  13. * @name apply
  14. * @static
  15. * @memberOf module:Utils
  16. * @method
  17. * @category Util
  18. * @param {Function} fn - The function you want to eventually apply all
  19. * arguments to. Invokes with (arguments...).
  20. * @param {...*} arguments... - Any number of arguments to automatically apply
  21. * when the continuation is called.
  22. * @returns {Function} the partially-applied function
  23. * @example
  24. *
  25. * // using apply
  26. * 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 apply
  33. * 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 the
  43. * // continuation:
  44. *
  45. * node> var fn = async.apply(sys.puts, 'one');
  46. * node> fn('two', 'three');
  47. * one
  48. * two
  49. * three
  50. */
  51. function apply(fn, ...args) {
  52. return (...callArgs) => fn(...args,...callArgs);
  53. }
  54. function initialParams (fn) {
  55. return function (...args/*, callback*/) {
  56. var callback = args.pop();
  57. return fn.call(this, args, callback);
  58. };
  59. }
  60. var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
  61. var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
  62. function fallback(fn) {
  63. setTimeout(fn, 0);
  64. }
  65. function wrap(defer) {
  66. return (fn, ...args) => defer(() => fn(...args));
  67. }
  68. var _defer;
  69. if (hasSetImmediate) {
  70. _defer = setImmediate;
  71. } else if (hasNextTick) {
  72. _defer = process.nextTick;
  73. } else {
  74. _defer = fallback;
  75. }
  76. var setImmediate$1 = wrap(_defer);
  77. /**
  78. * Take a sync function and make it async, passing its return value to a
  79. * callback. This is useful for plugging sync functions into a waterfall,
  80. * series, or other async functions. Any arguments passed to the generated
  81. * function will be passed to the wrapped function (except for the final
  82. * callback argument). Errors thrown will be passed to the callback.
  83. *
  84. * If the function passed to `asyncify` returns a Promise, that promises's
  85. * resolved/rejected state will be used to call the callback, rather than simply
  86. * the synchronous return value.
  87. *
  88. * This also means you can asyncify ES2017 `async` functions.
  89. *
  90. * @name asyncify
  91. * @static
  92. * @memberOf module:Utils
  93. * @method
  94. * @alias wrapSync
  95. * @category Util
  96. * @param {Function} func - The synchronous function, or Promise-returning
  97. * function to convert to an {@link AsyncFunction}.
  98. * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
  99. * invoked with `(args..., callback)`.
  100. * @example
  101. *
  102. * // passing a regular synchronous function
  103. * async.waterfall([
  104. * async.apply(fs.readFile, filename, "utf8"),
  105. * async.asyncify(JSON.parse),
  106. * function (data, next) {
  107. * // data is the result of parsing the text.
  108. * // If there was a parsing error, it would have been caught.
  109. * }
  110. * ], callback);
  111. *
  112. * // passing a function returning a promise
  113. * async.waterfall([
  114. * async.apply(fs.readFile, filename, "utf8"),
  115. * async.asyncify(function (contents) {
  116. * return db.model.create(contents);
  117. * }),
  118. * function (model, next) {
  119. * // `model` is the instantiated model object.
  120. * // If there was an error, this function would be skipped.
  121. * }
  122. * ], callback);
  123. *
  124. * // es2017 example, though `asyncify` is not needed if your JS environment
  125. * // supports async functions out of the box
  126. * var q = async.queue(async.asyncify(async function(file) {
  127. * var intermediateStep = await processFile(file);
  128. * return await somePromise(intermediateStep)
  129. * }));
  130. *
  131. * q.push(files);
  132. */
  133. function asyncify(func) {
  134. if (isAsync(func)) {
  135. return function (...args/*, callback*/) {
  136. const callback = args.pop();
  137. const promise = func.apply(this, args);
  138. return handlePromise(promise, callback)
  139. }
  140. }
  141. return initialParams(function (args, callback) {
  142. var result;
  143. try {
  144. result = func.apply(this, args);
  145. } catch (e) {
  146. return callback(e);
  147. }
  148. // if result is Promise object
  149. if (result && typeof result.then === 'function') {
  150. return handlePromise(result, callback)
  151. } else {
  152. callback(null, result);
  153. }
  154. });
  155. }
  156. function handlePromise(promise, callback) {
  157. return promise.then(value => {
  158. invokeCallback(callback, null, value);
  159. }, err => {
  160. invokeCallback(callback, err && err.message ? err : new Error(err));
  161. });
  162. }
  163. function invokeCallback(callback, error, value) {
  164. try {
  165. callback(error, value);
  166. } catch (err) {
  167. setImmediate$1(e => { throw e }, err);
  168. }
  169. }
  170. function isAsync(fn) {
  171. return fn[Symbol.toStringTag] === 'AsyncFunction';
  172. }
  173. function isAsyncGenerator(fn) {
  174. return fn[Symbol.toStringTag] === 'AsyncGenerator';
  175. }
  176. function isAsyncIterable(obj) {
  177. return typeof obj[Symbol.asyncIterator] === 'function';
  178. }
  179. function wrapAsync(asyncFn) {
  180. if (typeof asyncFn !== 'function') throw new Error('expected a function')
  181. return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;
  182. }
  183. function applyEach(eachfn) {
  184. return function(fns, ...callArgs) {
  185. var go = initialParams(function(args, callback) {
  186. var that = this;
  187. return eachfn(fns, (fn, cb) => {
  188. wrapAsync(fn).apply(that, args.concat(cb));
  189. }, callback);
  190. });
  191. if (callArgs.length) {
  192. return go.apply(this, callArgs);
  193. }
  194. return go;
  195. };
  196. }
  197. function _asyncMap(eachfn, arr, iteratee, callback) {
  198. arr = arr || [];
  199. var results = [];
  200. var counter = 0;
  201. var _iteratee = wrapAsync(iteratee);
  202. return eachfn(arr, (value, _, iterCb) => {
  203. var index = counter++;
  204. _iteratee(value, (err, v) => {
  205. results[index] = v;
  206. iterCb(err);
  207. });
  208. }, err => {
  209. callback(err, results);
  210. });
  211. }
  212. function isArrayLike(value) {
  213. return value &&
  214. typeof value.length === 'number' &&
  215. value.length >= 0 &&
  216. value.length % 1 === 0;
  217. }
  218. // A temporary value used to identify if the loop should be broken.
  219. // See #1064, #1293
  220. const breakLoop = {};
  221. function once(fn) {
  222. function wrapper (...args) {
  223. if (fn === null) return;
  224. var callFn = fn;
  225. fn = null;
  226. callFn.apply(this, args);
  227. }
  228. Object.assign(wrapper, fn);
  229. return wrapper
  230. }
  231. function getIterator (coll) {
  232. return coll[Symbol.iterator] && coll[Symbol.iterator]();
  233. }
  234. function createArrayIterator(coll) {
  235. var i = -1;
  236. var len = coll.length;
  237. return function next() {
  238. return ++i < len ? {value: coll[i], key: i} : null;
  239. }
  240. }
  241. function createES2015Iterator(iterator) {
  242. var i = -1;
  243. return function next() {
  244. var item = iterator.next();
  245. if (item.done)
  246. return null;
  247. i++;
  248. return {value: item.value, key: i};
  249. }
  250. }
  251. function createObjectIterator(obj) {
  252. var okeys = obj ? Object.keys(obj) : [];
  253. var i = -1;
  254. var len = okeys.length;
  255. return function next() {
  256. var key = okeys[++i];
  257. return i < len ? {value: obj[key], key} : null;
  258. };
  259. }
  260. function createIterator(coll) {
  261. if (isArrayLike(coll)) {
  262. return createArrayIterator(coll);
  263. }
  264. var iterator = getIterator(coll);
  265. return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
  266. }
  267. function onlyOnce(fn) {
  268. return function (...args) {
  269. if (fn === null) throw new Error("Callback was already called.");
  270. var callFn = fn;
  271. fn = null;
  272. callFn.apply(this, args);
  273. };
  274. }
  275. // for async generators
  276. function asyncEachOfLimit(generator, limit, iteratee, callback) {
  277. let done = false;
  278. let canceled = false;
  279. let awaiting = false;
  280. let running = 0;
  281. let idx = 0;
  282. function replenish() {
  283. //console.log('replenish')
  284. if (running >= limit || awaiting || done) return
  285. //console.log('replenish awaiting')
  286. awaiting = true;
  287. generator.next().then(({value, done: iterDone}) => {
  288. //console.log('got value', value)
  289. if (canceled || done) return
  290. awaiting = false;
  291. if (iterDone) {
  292. done = true;
  293. if (running <= 0) {
  294. //console.log('done nextCb')
  295. callback(null);
  296. }
  297. return;
  298. }
  299. running++;
  300. iteratee(value, idx, iterateeCallback);
  301. idx++;
  302. replenish();
  303. }).catch(handleError);
  304. }
  305. function iterateeCallback(err, result) {
  306. //console.log('iterateeCallback')
  307. running -= 1;
  308. if (canceled) return
  309. if (err) return handleError(err)
  310. if (err === false) {
  311. done = true;
  312. canceled = true;
  313. return
  314. }
  315. if (result === breakLoop || (done && running <= 0)) {
  316. done = true;
  317. //console.log('done iterCb')
  318. return callback(null);
  319. }
  320. replenish();
  321. }
  322. function handleError(err) {
  323. if (canceled) return
  324. awaiting = false;
  325. done = true;
  326. callback(err);
  327. }
  328. replenish();
  329. }
  330. var eachOfLimit = (limit) => {
  331. return (obj, iteratee, callback) => {
  332. callback = once(callback);
  333. if (limit <= 0) {
  334. throw new RangeError('concurrency limit cannot be less than 1')
  335. }
  336. if (!obj) {
  337. return callback(null);
  338. }
  339. if (isAsyncGenerator(obj)) {
  340. return asyncEachOfLimit(obj, limit, iteratee, callback)
  341. }
  342. if (isAsyncIterable(obj)) {
  343. return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback)
  344. }
  345. var nextElem = createIterator(obj);
  346. var done = false;
  347. var canceled = false;
  348. var running = 0;
  349. var looping = false;
  350. function iterateeCallback(err, value) {
  351. if (canceled) return
  352. running -= 1;
  353. if (err) {
  354. done = true;
  355. callback(err);
  356. }
  357. else if (err === false) {
  358. done = true;
  359. canceled = true;
  360. }
  361. else if (value === breakLoop || (done && running <= 0)) {
  362. done = true;
  363. return callback(null);
  364. }
  365. else if (!looping) {
  366. replenish();
  367. }
  368. }
  369. function replenish () {
  370. looping = true;
  371. while (running < limit && !done) {
  372. var elem = nextElem();
  373. if (elem === null) {
  374. done = true;
  375. if (running <= 0) {
  376. callback(null);
  377. }
  378. return;
  379. }
  380. running += 1;
  381. iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
  382. }
  383. looping = false;
  384. }
  385. replenish();
  386. };
  387. };
  388. // conditionally promisify a function.
  389. // only return a promise if a callback is omitted
  390. function awaitify (asyncFn, arity = asyncFn.length) {
  391. if (!arity) throw new Error('arity is undefined')
  392. function awaitable (...args) {
  393. if (typeof args[arity - 1] === 'function') {
  394. return asyncFn.apply(this, args)
  395. }
  396. return new Promise((resolve, reject) => {
  397. args[arity - 1] = (err, ...cbArgs) => {
  398. if (err) return reject(err)
  399. resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
  400. };
  401. asyncFn.apply(this, args);
  402. })
  403. }
  404. Object.defineProperty(awaitable, 'name', {
  405. value: `awaitable(${asyncFn.name})`
  406. });
  407. return awaitable
  408. }
  409. /**
  410. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
  411. * time.
  412. *
  413. * @name eachOfLimit
  414. * @static
  415. * @memberOf module:Collections
  416. * @method
  417. * @see [async.eachOf]{@link module:Collections.eachOf}
  418. * @alias forEachOfLimit
  419. * @category Collection
  420. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  421. * @param {number} limit - The maximum number of async operations at a time.
  422. * @param {AsyncFunction} iteratee - An async function to apply to each
  423. * item in `coll`. The `key` is the item's key, or index in the case of an
  424. * array.
  425. * Invoked with (item, key, callback).
  426. * @param {Function} [callback] - A callback which is called when all
  427. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  428. * @returns {Promise} a promise, if a callback is omitted
  429. */
  430. function eachOfLimit$1(coll, limit, iteratee, callback) {
  431. return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);
  432. }
  433. var eachOfLimit$2 = awaitify(eachOfLimit$1, 4);
  434. // eachOf implementation optimized for array-likes
  435. function eachOfArrayLike(coll, iteratee, callback) {
  436. callback = once(callback);
  437. var index = 0,
  438. completed = 0,
  439. {length} = coll,
  440. canceled = false;
  441. if (length === 0) {
  442. callback(null);
  443. }
  444. function iteratorCallback(err, value) {
  445. if (err === false) {
  446. canceled = true;
  447. }
  448. if (canceled === true) return
  449. if (err) {
  450. callback(err);
  451. } else if ((++completed === length) || value === breakLoop) {
  452. callback(null);
  453. }
  454. }
  455. for (; index < length; index++) {
  456. iteratee(coll[index], index, onlyOnce(iteratorCallback));
  457. }
  458. }
  459. // a generic version of eachOf which can handle array, object, and iterator cases.
  460. function eachOfGeneric (coll, iteratee, callback) {
  461. return eachOfLimit$2(coll, Infinity, iteratee, callback);
  462. }
  463. /**
  464. * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
  465. * to the iteratee.
  466. *
  467. * @name eachOf
  468. * @static
  469. * @memberOf module:Collections
  470. * @method
  471. * @alias forEachOf
  472. * @category Collection
  473. * @see [async.each]{@link module:Collections.each}
  474. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  475. * @param {AsyncFunction} iteratee - A function to apply to each
  476. * item in `coll`.
  477. * The `key` is the item's key, or index in the case of an array.
  478. * Invoked with (item, key, callback).
  479. * @param {Function} [callback] - A callback which is called when all
  480. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  481. * @returns {Promise} a promise, if a callback is omitted
  482. * @example
  483. *
  484. * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
  485. * var configs = {};
  486. *
  487. * async.forEachOf(obj, function (value, key, callback) {
  488. * fs.readFile(__dirname + value, "utf8", function (err, data) {
  489. * if (err) return callback(err);
  490. * try {
  491. * configs[key] = JSON.parse(data);
  492. * } catch (e) {
  493. * return callback(e);
  494. * }
  495. * callback();
  496. * });
  497. * }, function (err) {
  498. * if (err) console.error(err.message);
  499. * // configs is now a map of JSON data
  500. * doSomethingWith(configs);
  501. * });
  502. */
  503. function eachOf(coll, iteratee, callback) {
  504. var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
  505. return eachOfImplementation(coll, wrapAsync(iteratee), callback);
  506. }
  507. var eachOf$1 = awaitify(eachOf, 3);
  508. /**
  509. * Produces a new collection of values by mapping each value in `coll` through
  510. * the `iteratee` function. The `iteratee` is called with an item from `coll`
  511. * and a callback for when it has finished processing. Each of these callback
  512. * takes 2 arguments: an `error`, and the transformed item from `coll`. If
  513. * `iteratee` passes an error to its callback, the main `callback` (for the
  514. * `map` function) is immediately called with the error.
  515. *
  516. * Note, that since this function applies the `iteratee` to each item in
  517. * parallel, there is no guarantee that the `iteratee` functions will complete
  518. * in order. However, the results array will be in the same order as the
  519. * original `coll`.
  520. *
  521. * If `map` is passed an Object, the results will be an Array. The results
  522. * will roughly be in the order of the original Objects' keys (but this can
  523. * vary across JavaScript engines).
  524. *
  525. * @name map
  526. * @static
  527. * @memberOf module:Collections
  528. * @method
  529. * @category Collection
  530. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  531. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  532. * `coll`.
  533. * The iteratee should complete with the transformed item.
  534. * Invoked with (item, callback).
  535. * @param {Function} [callback] - A callback which is called when all `iteratee`
  536. * functions have finished, or an error occurs. Results is an Array of the
  537. * transformed items from the `coll`. Invoked with (err, results).
  538. * @returns {Promise} a promise, if no callback is passed
  539. * @example
  540. *
  541. * async.map(['file1','file2','file3'], fs.stat, function(err, results) {
  542. * // results is now an array of stats for each file
  543. * });
  544. */
  545. function map (coll, iteratee, callback) {
  546. return _asyncMap(eachOf$1, coll, iteratee, callback)
  547. }
  548. var map$1 = awaitify(map, 3);
  549. /**
  550. * Applies the provided arguments to each function in the array, calling
  551. * `callback` after all functions have completed. If you only provide the first
  552. * argument, `fns`, then it will return a function which lets you pass in the
  553. * arguments as if it were a single function call. If more arguments are
  554. * provided, `callback` is required while `args` is still optional. The results
  555. * for each of the applied async functions are passed to the final callback
  556. * as an array.
  557. *
  558. * @name applyEach
  559. * @static
  560. * @memberOf module:ControlFlow
  561. * @method
  562. * @category Control Flow
  563. * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s
  564. * to all call with the same arguments
  565. * @param {...*} [args] - any number of separate arguments to pass to the
  566. * function.
  567. * @param {Function} [callback] - the final argument should be the callback,
  568. * called when all functions have completed processing.
  569. * @returns {Function} - If only the first argument, `fns`, is provided, it will
  570. * return a function which lets you pass in the arguments as if it were a single
  571. * function call. The signature is `(..args, callback)`. If invoked with any
  572. * arguments, `callback` is required.
  573. * @example
  574. *
  575. * async.applyEach([enableSearch, updateSchema], 'bucket', (err, results) => {
  576. * // results[0] is the results for `enableSearch`
  577. * // results[1] is the results for `updateSchema`
  578. * });
  579. *
  580. * // partial application example:
  581. * async.each(
  582. * buckets,
  583. * async.applyEach([enableSearch, updateSchema]),
  584. * callback
  585. * );
  586. */
  587. var applyEach$1 = applyEach(map$1);
  588. /**
  589. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
  590. *
  591. * @name eachOfSeries
  592. * @static
  593. * @memberOf module:Collections
  594. * @method
  595. * @see [async.eachOf]{@link module:Collections.eachOf}
  596. * @alias forEachOfSeries
  597. * @category Collection
  598. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  599. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  600. * `coll`.
  601. * Invoked with (item, key, callback).
  602. * @param {Function} [callback] - A callback which is called when all `iteratee`
  603. * functions have finished, or an error occurs. Invoked with (err).
  604. * @returns {Promise} a promise, if a callback is omitted
  605. */
  606. function eachOfSeries(coll, iteratee, callback) {
  607. return eachOfLimit$2(coll, 1, iteratee, callback)
  608. }
  609. var eachOfSeries$1 = awaitify(eachOfSeries, 3);
  610. /**
  611. * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
  612. *
  613. * @name mapSeries
  614. * @static
  615. * @memberOf module:Collections
  616. * @method
  617. * @see [async.map]{@link module:Collections.map}
  618. * @category Collection
  619. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  620. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  621. * `coll`.
  622. * The iteratee should complete with the transformed item.
  623. * Invoked with (item, callback).
  624. * @param {Function} [callback] - A callback which is called when all `iteratee`
  625. * functions have finished, or an error occurs. Results is an array of the
  626. * transformed items from the `coll`. Invoked with (err, results).
  627. * @returns {Promise} a promise, if no callback is passed
  628. */
  629. function mapSeries (coll, iteratee, callback) {
  630. return _asyncMap(eachOfSeries$1, coll, iteratee, callback)
  631. }
  632. var mapSeries$1 = awaitify(mapSeries, 3);
  633. /**
  634. * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.
  635. *
  636. * @name applyEachSeries
  637. * @static
  638. * @memberOf module:ControlFlow
  639. * @method
  640. * @see [async.applyEach]{@link module:ControlFlow.applyEach}
  641. * @category Control Flow
  642. * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all
  643. * call with the same arguments
  644. * @param {...*} [args] - any number of separate arguments to pass to the
  645. * function.
  646. * @param {Function} [callback] - the final argument should be the callback,
  647. * called when all functions have completed processing.
  648. * @returns {Function} - If only the first argument is provided, it will return
  649. * a function which lets you pass in the arguments as if it were a single
  650. * function call.
  651. */
  652. var applyEachSeries = applyEach(mapSeries$1);
  653. const PROMISE_SYMBOL = Symbol('promiseCallback');
  654. function promiseCallback () {
  655. let resolve, reject;
  656. function callback (err, ...args) {
  657. if (err) return reject(err)
  658. resolve(args.length > 1 ? args : args[0]);
  659. }
  660. callback[PROMISE_SYMBOL] = new Promise((res, rej) => {
  661. resolve = res,
  662. reject = rej;
  663. });
  664. return callback
  665. }
  666. /**
  667. * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on
  668. * their requirements. Each function can optionally depend on other functions
  669. * being completed first, and each function is run as soon as its requirements
  670. * are satisfied.
  671. *
  672. * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence
  673. * will stop. Further tasks will not execute (so any other functions depending
  674. * on it will not run), and the main `callback` is immediately called with the
  675. * error.
  676. *
  677. * {@link AsyncFunction}s also receive an object containing the results of functions which
  678. * have completed so far as the first argument, if they have dependencies. If a
  679. * task function has no dependencies, it will only be passed a callback.
  680. *
  681. * @name auto
  682. * @static
  683. * @memberOf module:ControlFlow
  684. * @method
  685. * @category Control Flow
  686. * @param {Object} tasks - An object. Each of its properties is either a
  687. * function or an array of requirements, with the {@link AsyncFunction} itself the last item
  688. * in the array. The object's key of a property serves as the name of the task
  689. * defined by that property, i.e. can be used when specifying requirements for
  690. * other tasks. The function receives one or two arguments:
  691. * * a `results` object, containing the results of the previously executed
  692. * functions, only passed if the task has any dependencies,
  693. * * a `callback(err, result)` function, which must be called when finished,
  694. * passing an `error` (which can be `null`) and the result of the function's
  695. * execution.
  696. * @param {number} [concurrency=Infinity] - An optional `integer` for
  697. * determining the maximum number of tasks that can be run in parallel. By
  698. * default, as many as possible.
  699. * @param {Function} [callback] - An optional callback which is called when all
  700. * the tasks have been completed. It receives the `err` argument if any `tasks`
  701. * pass an error to their callback. Results are always returned; however, if an
  702. * error occurs, no further `tasks` will be performed, and the results object
  703. * will only contain partial results. Invoked with (err, results).
  704. * @returns {Promise} a promise, if a callback is not passed
  705. * @example
  706. *
  707. * async.auto({
  708. * // this function will just be passed a callback
  709. * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
  710. * showData: ['readData', function(results, cb) {
  711. * // results.readData is the file's contents
  712. * // ...
  713. * }]
  714. * }, callback);
  715. *
  716. * async.auto({
  717. * get_data: function(callback) {
  718. * console.log('in get_data');
  719. * // async code to get some data
  720. * callback(null, 'data', 'converted to array');
  721. * },
  722. * make_folder: function(callback) {
  723. * console.log('in make_folder');
  724. * // async code to create a directory to store a file in
  725. * // this is run at the same time as getting the data
  726. * callback(null, 'folder');
  727. * },
  728. * write_file: ['get_data', 'make_folder', function(results, callback) {
  729. * console.log('in write_file', JSON.stringify(results));
  730. * // once there is some data and the directory exists,
  731. * // write the data to a file in the directory
  732. * callback(null, 'filename');
  733. * }],
  734. * email_link: ['write_file', function(results, callback) {
  735. * console.log('in email_link', JSON.stringify(results));
  736. * // once the file is written let's email a link to it...
  737. * // results.write_file contains the filename returned by write_file.
  738. * callback(null, {'file':results.write_file, 'email':'user@example.com'});
  739. * }]
  740. * }, function(err, results) {
  741. * console.log('err = ', err);
  742. * console.log('results = ', results);
  743. * });
  744. */
  745. function auto(tasks, concurrency, callback) {
  746. if (typeof concurrency !== 'number') {
  747. // concurrency is optional, shift the args.
  748. callback = concurrency;
  749. concurrency = null;
  750. }
  751. callback = once(callback || promiseCallback());
  752. var numTasks = Object.keys(tasks).length;
  753. if (!numTasks) {
  754. return callback(null);
  755. }
  756. if (!concurrency) {
  757. concurrency = numTasks;
  758. }
  759. var results = {};
  760. var runningTasks = 0;
  761. var canceled = false;
  762. var hasError = false;
  763. var listeners = Object.create(null);
  764. var readyTasks = [];
  765. // for cycle detection:
  766. var readyToCheck = []; // tasks that have been identified as reachable
  767. // without the possibility of returning to an ancestor task
  768. var uncheckedDependencies = {};
  769. Object.keys(tasks).forEach(key => {
  770. var task = tasks[key];
  771. if (!Array.isArray(task)) {
  772. // no dependencies
  773. enqueueTask(key, [task]);
  774. readyToCheck.push(key);
  775. return;
  776. }
  777. var dependencies = task.slice(0, task.length - 1);
  778. var remainingDependencies = dependencies.length;
  779. if (remainingDependencies === 0) {
  780. enqueueTask(key, task);
  781. readyToCheck.push(key);
  782. return;
  783. }
  784. uncheckedDependencies[key] = remainingDependencies;
  785. dependencies.forEach(dependencyName => {
  786. if (!tasks[dependencyName]) {
  787. throw new Error('async.auto task `' + key +
  788. '` has a non-existent dependency `' +
  789. dependencyName + '` in ' +
  790. dependencies.join(', '));
  791. }
  792. addListener(dependencyName, () => {
  793. remainingDependencies--;
  794. if (remainingDependencies === 0) {
  795. enqueueTask(key, task);
  796. }
  797. });
  798. });
  799. });
  800. checkForDeadlocks();
  801. processQueue();
  802. function enqueueTask(key, task) {
  803. readyTasks.push(() => runTask(key, task));
  804. }
  805. function processQueue() {
  806. if (canceled) return
  807. if (readyTasks.length === 0 && runningTasks === 0) {
  808. return callback(null, results);
  809. }
  810. while(readyTasks.length && runningTasks < concurrency) {
  811. var run = readyTasks.shift();
  812. run();
  813. }
  814. }
  815. function addListener(taskName, fn) {
  816. var taskListeners = listeners[taskName];
  817. if (!taskListeners) {
  818. taskListeners = listeners[taskName] = [];
  819. }
  820. taskListeners.push(fn);
  821. }
  822. function taskComplete(taskName) {
  823. var taskListeners = listeners[taskName] || [];
  824. taskListeners.forEach(fn => fn());
  825. processQueue();
  826. }
  827. function runTask(key, task) {
  828. if (hasError) return;
  829. var taskCallback = onlyOnce((err, ...result) => {
  830. runningTasks--;
  831. if (err === false) {
  832. canceled = true;
  833. return
  834. }
  835. if (result.length < 2) {
  836. [result] = result;
  837. }
  838. if (err) {
  839. var safeResults = {};
  840. Object.keys(results).forEach(rkey => {
  841. safeResults[rkey] = results[rkey];
  842. });
  843. safeResults[key] = result;
  844. hasError = true;
  845. listeners = Object.create(null);
  846. if (canceled) return
  847. callback(err, safeResults);
  848. } else {
  849. results[key] = result;
  850. taskComplete(key);
  851. }
  852. });
  853. runningTasks++;
  854. var taskFn = wrapAsync(task[task.length - 1]);
  855. if (task.length > 1) {
  856. taskFn(results, taskCallback);
  857. } else {
  858. taskFn(taskCallback);
  859. }
  860. }
  861. function checkForDeadlocks() {
  862. // Kahn's algorithm
  863. // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm
  864. // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html
  865. var currentTask;
  866. var counter = 0;
  867. while (readyToCheck.length) {
  868. currentTask = readyToCheck.pop();
  869. counter++;
  870. getDependents(currentTask).forEach(dependent => {
  871. if (--uncheckedDependencies[dependent] === 0) {
  872. readyToCheck.push(dependent);
  873. }
  874. });
  875. }
  876. if (counter !== numTasks) {
  877. throw new Error(
  878. 'async.auto cannot execute tasks due to a recursive dependency'
  879. );
  880. }
  881. }
  882. function getDependents(taskName) {
  883. var result = [];
  884. Object.keys(tasks).forEach(key => {
  885. const task = tasks[key];
  886. if (Array.isArray(task) && task.indexOf(taskName) >= 0) {
  887. result.push(key);
  888. }
  889. });
  890. return result;
  891. }
  892. return callback[PROMISE_SYMBOL]
  893. }
  894. var FN_ARGS = /^(?:async\s+)?(?:function)?\s*[^(]*\(\s*([^)]+)\s*\)(?:\s*{)/m;
  895. var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)^=]+)\s*\)?(?:\s*=>)/m;
  896. var FN_ARG_SPLIT = /,/;
  897. var FN_ARG = /(=.+)?(\s*)$/;
  898. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  899. function parseParams(func) {
  900. const src = func.toString().replace(STRIP_COMMENTS, '');
  901. let match = src.match(FN_ARGS);
  902. if (!match) {
  903. match = src.match(ARROW_FN_ARGS);
  904. }
  905. if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src)
  906. let [, args] = match;
  907. return args
  908. .replace(/\s/g, '')
  909. .split(FN_ARG_SPLIT)
  910. .map((arg) => arg.replace(FN_ARG, '').trim());
  911. }
  912. /**
  913. * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent
  914. * tasks are specified as parameters to the function, after the usual callback
  915. * parameter, with the parameter names matching the names of the tasks it
  916. * depends on. This can provide even more readable task graphs which can be
  917. * easier to maintain.
  918. *
  919. * If a final callback is specified, the task results are similarly injected,
  920. * specified as named parameters after the initial error parameter.
  921. *
  922. * The autoInject function is purely syntactic sugar and its semantics are
  923. * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.
  924. *
  925. * @name autoInject
  926. * @static
  927. * @memberOf module:ControlFlow
  928. * @method
  929. * @see [async.auto]{@link module:ControlFlow.auto}
  930. * @category Control Flow
  931. * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of
  932. * the form 'func([dependencies...], callback). The object's key of a property
  933. * serves as the name of the task defined by that property, i.e. can be used
  934. * when specifying requirements for other tasks.
  935. * * The `callback` parameter is a `callback(err, result)` which must be called
  936. * when finished, passing an `error` (which can be `null`) and the result of
  937. * the function's execution. The remaining parameters name other tasks on
  938. * which the task is dependent, and the results from those tasks are the
  939. * arguments of those parameters.
  940. * @param {Function} [callback] - An optional callback which is called when all
  941. * the tasks have been completed. It receives the `err` argument if any `tasks`
  942. * pass an error to their callback, and a `results` object with any completed
  943. * task results, similar to `auto`.
  944. * @returns {Promise} a promise, if no callback is passed
  945. * @example
  946. *
  947. * // The example from `auto` can be rewritten as follows:
  948. * async.autoInject({
  949. * get_data: function(callback) {
  950. * // async code to get some data
  951. * callback(null, 'data', 'converted to array');
  952. * },
  953. * make_folder: function(callback) {
  954. * // async code to create a directory to store a file in
  955. * // this is run at the same time as getting the data
  956. * callback(null, 'folder');
  957. * },
  958. * write_file: function(get_data, make_folder, callback) {
  959. * // once there is some data and the directory exists,
  960. * // write the data to a file in the directory
  961. * callback(null, 'filename');
  962. * },
  963. * email_link: function(write_file, callback) {
  964. * // once the file is written let's email a link to it...
  965. * // write_file contains the filename returned by write_file.
  966. * callback(null, {'file':write_file, 'email':'user@example.com'});
  967. * }
  968. * }, function(err, results) {
  969. * console.log('err = ', err);
  970. * console.log('email_link = ', results.email_link);
  971. * });
  972. *
  973. * // If you are using a JS minifier that mangles parameter names, `autoInject`
  974. * // will not work with plain functions, since the parameter names will be
  975. * // collapsed to a single letter identifier. To work around this, you can
  976. * // explicitly specify the names of the parameters your task function needs
  977. * // in an array, similar to Angular.js dependency injection.
  978. *
  979. * // This still has an advantage over plain `auto`, since the results a task
  980. * // depends on are still spread into arguments.
  981. * async.autoInject({
  982. * //...
  983. * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
  984. * callback(null, 'filename');
  985. * }],
  986. * email_link: ['write_file', function(write_file, callback) {
  987. * callback(null, {'file':write_file, 'email':'user@example.com'});
  988. * }]
  989. * //...
  990. * }, function(err, results) {
  991. * console.log('err = ', err);
  992. * console.log('email_link = ', results.email_link);
  993. * });
  994. */
  995. function autoInject(tasks, callback) {
  996. var newTasks = {};
  997. Object.keys(tasks).forEach(key => {
  998. var taskFn = tasks[key];
  999. var params;
  1000. var fnIsAsync = isAsync(taskFn);
  1001. var hasNoDeps =
  1002. (!fnIsAsync && taskFn.length === 1) ||
  1003. (fnIsAsync && taskFn.length === 0);
  1004. if (Array.isArray(taskFn)) {
  1005. params = [...taskFn];
  1006. taskFn = params.pop();
  1007. newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
  1008. } else if (hasNoDeps) {
  1009. // no dependencies, use the function as-is
  1010. newTasks[key] = taskFn;
  1011. } else {
  1012. params = parseParams(taskFn);
  1013. if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) {
  1014. throw new Error("autoInject task functions require explicit parameters.");
  1015. }
  1016. // remove callback param
  1017. if (!fnIsAsync) params.pop();
  1018. newTasks[key] = params.concat(newTask);
  1019. }
  1020. function newTask(results, taskCb) {
  1021. var newArgs = params.map(name => results[name]);
  1022. newArgs.push(taskCb);
  1023. wrapAsync(taskFn)(...newArgs);
  1024. }
  1025. });
  1026. return auto(newTasks, callback);
  1027. }
  1028. // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
  1029. // used for queues. This implementation assumes that the node provided by the user can be modified
  1030. // to adjust the next and last properties. We implement only the minimal functionality
  1031. // for queue support.
  1032. class DLL {
  1033. constructor() {
  1034. this.head = this.tail = null;
  1035. this.length = 0;
  1036. }
  1037. removeLink(node) {
  1038. if (node.prev) node.prev.next = node.next;
  1039. else this.head = node.next;
  1040. if (node.next) node.next.prev = node.prev;
  1041. else this.tail = node.prev;
  1042. node.prev = node.next = null;
  1043. this.length -= 1;
  1044. return node;
  1045. }
  1046. empty () {
  1047. while(this.head) this.shift();
  1048. return this;
  1049. }
  1050. insertAfter(node, newNode) {
  1051. newNode.prev = node;
  1052. newNode.next = node.next;
  1053. if (node.next) node.next.prev = newNode;
  1054. else this.tail = newNode;
  1055. node.next = newNode;
  1056. this.length += 1;
  1057. }
  1058. insertBefore(node, newNode) {
  1059. newNode.prev = node.prev;
  1060. newNode.next = node;
  1061. if (node.prev) node.prev.next = newNode;
  1062. else this.head = newNode;
  1063. node.prev = newNode;
  1064. this.length += 1;
  1065. }
  1066. unshift(node) {
  1067. if (this.head) this.insertBefore(this.head, node);
  1068. else setInitial(this, node);
  1069. }
  1070. push(node) {
  1071. if (this.tail) this.insertAfter(this.tail, node);
  1072. else setInitial(this, node);
  1073. }
  1074. shift() {
  1075. return this.head && this.removeLink(this.head);
  1076. }
  1077. pop() {
  1078. return this.tail && this.removeLink(this.tail);
  1079. }
  1080. toArray() {
  1081. return [...this]
  1082. }
  1083. *[Symbol.iterator] () {
  1084. var cur = this.head;
  1085. while (cur) {
  1086. yield cur.data;
  1087. cur = cur.next;
  1088. }
  1089. }
  1090. remove (testFn) {
  1091. var curr = this.head;
  1092. while(curr) {
  1093. var {next} = curr;
  1094. if (testFn(curr)) {
  1095. this.removeLink(curr);
  1096. }
  1097. curr = next;
  1098. }
  1099. return this;
  1100. }
  1101. }
  1102. function setInitial(dll, node) {
  1103. dll.length = 1;
  1104. dll.head = dll.tail = node;
  1105. }
  1106. const noop = () => {};
  1107. function queue(worker, concurrency, payload) {
  1108. if (concurrency == null) {
  1109. concurrency = 1;
  1110. }
  1111. else if(concurrency === 0) {
  1112. throw new RangeError('Concurrency must not be zero');
  1113. }
  1114. var _worker = wrapAsync(worker);
  1115. var numRunning = 0;
  1116. var workersList = [];
  1117. var processingScheduled = false;
  1118. function _insert(data, insertAtFront, callback) {
  1119. if (callback != null && typeof callback !== 'function') {
  1120. throw new Error('task callback must be a function');
  1121. }
  1122. q.started = true;
  1123. if (!Array.isArray(data)) {
  1124. data = [data];
  1125. }
  1126. if (data.length === 0 && q.idle()) {
  1127. // call drain immediately if there are no tasks
  1128. return setImmediate$1(() => q.drain());
  1129. }
  1130. for (var i = 0, l = data.length; i < l; i++) {
  1131. var item = {
  1132. data: data[i],
  1133. callback: callback || noop
  1134. };
  1135. if (insertAtFront) {
  1136. q._tasks.unshift(item);
  1137. } else {
  1138. q._tasks.push(item);
  1139. }
  1140. }
  1141. if (!processingScheduled) {
  1142. processingScheduled = true;
  1143. setImmediate$1(() => {
  1144. processingScheduled = false;
  1145. q.process();
  1146. });
  1147. }
  1148. }
  1149. function _next(tasks) {
  1150. return function (err, ...args) {
  1151. numRunning -= 1;
  1152. for (var i = 0, l = tasks.length; i < l; i++) {
  1153. var task = tasks[i];
  1154. var index = workersList.indexOf(task);
  1155. if (index === 0) {
  1156. workersList.shift();
  1157. } else if (index > 0) {
  1158. workersList.splice(index, 1);
  1159. }
  1160. task.callback(err, ...args);
  1161. if (err != null) {
  1162. q.error(err, task.data);
  1163. }
  1164. }
  1165. if (numRunning <= (q.concurrency - q.buffer) ) {
  1166. q.unsaturated();
  1167. }
  1168. if (q.idle()) {
  1169. q.drain();
  1170. }
  1171. q.process();
  1172. };
  1173. }
  1174. var isProcessing = false;
  1175. var q = {
  1176. _tasks: new DLL(),
  1177. *[Symbol.iterator] () {
  1178. yield* q._tasks[Symbol.iterator]();
  1179. },
  1180. concurrency,
  1181. payload,
  1182. saturated: noop,
  1183. unsaturated:noop,
  1184. buffer: concurrency / 4,
  1185. empty: noop,
  1186. drain: noop,
  1187. error: noop,
  1188. started: false,
  1189. paused: false,
  1190. push (data, callback) {
  1191. _insert(data, false, callback);
  1192. },
  1193. kill () {
  1194. q.drain = noop;
  1195. q._tasks.empty();
  1196. },
  1197. unshift (data, callback) {
  1198. _insert(data, true, callback);
  1199. },
  1200. remove (testFn) {
  1201. q._tasks.remove(testFn);
  1202. },
  1203. process () {
  1204. // Avoid trying to start too many processing operations. This can occur
  1205. // when callbacks resolve synchronously (#1267).
  1206. if (isProcessing) {
  1207. return;
  1208. }
  1209. isProcessing = true;
  1210. while(!q.paused && numRunning < q.concurrency && q._tasks.length){
  1211. var tasks = [], data = [];
  1212. var l = q._tasks.length;
  1213. if (q.payload) l = Math.min(l, q.payload);
  1214. for (var i = 0; i < l; i++) {
  1215. var node = q._tasks.shift();
  1216. tasks.push(node);
  1217. workersList.push(node);
  1218. data.push(node.data);
  1219. }
  1220. numRunning += 1;
  1221. if (q._tasks.length === 0) {
  1222. q.empty();
  1223. }
  1224. if (numRunning === q.concurrency) {
  1225. q.saturated();
  1226. }
  1227. var cb = onlyOnce(_next(tasks));
  1228. _worker(data, cb);
  1229. }
  1230. isProcessing = false;
  1231. },
  1232. length () {
  1233. return q._tasks.length;
  1234. },
  1235. running () {
  1236. return numRunning;
  1237. },
  1238. workersList () {
  1239. return workersList;
  1240. },
  1241. idle() {
  1242. return q._tasks.length + numRunning === 0;
  1243. },
  1244. pause () {
  1245. q.paused = true;
  1246. },
  1247. resume () {
  1248. if (q.paused === false) { return; }
  1249. q.paused = false;
  1250. setImmediate$1(q.process);
  1251. }
  1252. };
  1253. return q;
  1254. }
  1255. /**
  1256. * A cargo of tasks for the worker function to complete. Cargo inherits all of
  1257. * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}.
  1258. * @typedef {Object} CargoObject
  1259. * @memberOf module:ControlFlow
  1260. * @property {Function} length - A function returning the number of items
  1261. * waiting to be processed. Invoke like `cargo.length()`.
  1262. * @property {number} payload - An `integer` for determining how many tasks
  1263. * should be process per round. This property can be changed after a `cargo` is
  1264. * created to alter the payload on-the-fly.
  1265. * @property {Function} push - Adds `task` to the `queue`. The callback is
  1266. * called once the `worker` has finished processing the task. Instead of a
  1267. * single task, an array of `tasks` can be submitted. The respective callback is
  1268. * used for every task in the list. Invoke like `cargo.push(task, [callback])`.
  1269. * @property {Function} saturated - A callback that is called when the
  1270. * `queue.length()` hits the concurrency and further tasks will be queued.
  1271. * @property {Function} empty - A callback that is called when the last item
  1272. * from the `queue` is given to a `worker`.
  1273. * @property {Function} drain - A callback that is called when the last item
  1274. * from the `queue` has returned from the `worker`.
  1275. * @property {Function} idle - a function returning false if there are items
  1276. * waiting or being processed, or true if not. Invoke like `cargo.idle()`.
  1277. * @property {Function} pause - a function that pauses the processing of tasks
  1278. * until `resume()` is called. Invoke like `cargo.pause()`.
  1279. * @property {Function} resume - a function that resumes the processing of
  1280. * queued tasks when the queue is paused. Invoke like `cargo.resume()`.
  1281. * @property {Function} kill - a function that removes the `drain` callback and
  1282. * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`.
  1283. */
  1284. /**
  1285. * Creates a `cargo` object with the specified payload. Tasks added to the
  1286. * cargo will be processed altogether (up to the `payload` limit). If the
  1287. * `worker` is in progress, the task is queued until it becomes available. Once
  1288. * the `worker` has completed some tasks, each callback of those tasks is
  1289. * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
  1290. * for how `cargo` and `queue` work.
  1291. *
  1292. * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
  1293. * at a time, cargo passes an array of tasks to a single worker, repeating
  1294. * when the worker is finished.
  1295. *
  1296. * @name cargo
  1297. * @static
  1298. * @memberOf module:ControlFlow
  1299. * @method
  1300. * @see [async.queue]{@link module:ControlFlow.queue}
  1301. * @category Control Flow
  1302. * @param {AsyncFunction} worker - An asynchronous function for processing an array
  1303. * of queued tasks. Invoked with `(tasks, callback)`.
  1304. * @param {number} [payload=Infinity] - An optional `integer` for determining
  1305. * how many tasks should be processed per round; if omitted, the default is
  1306. * unlimited.
  1307. * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can
  1308. * attached as certain properties to listen for specific events during the
  1309. * lifecycle of the cargo and inner queue.
  1310. * @example
  1311. *
  1312. * // create a cargo object with payload 2
  1313. * var cargo = async.cargo(function(tasks, callback) {
  1314. * for (var i=0; i<tasks.length; i++) {
  1315. * console.log('hello ' + tasks[i].name);
  1316. * }
  1317. * callback();
  1318. * }, 2);
  1319. *
  1320. * // add some items
  1321. * cargo.push({name: 'foo'}, function(err) {
  1322. * console.log('finished processing foo');
  1323. * });
  1324. * cargo.push({name: 'bar'}, function(err) {
  1325. * console.log('finished processing bar');
  1326. * });
  1327. * cargo.push({name: 'baz'}, function(err) {
  1328. * console.log('finished processing baz');
  1329. * });
  1330. */
  1331. function cargo(worker, payload) {
  1332. return queue(worker, 1, payload);
  1333. }
  1334. /**
  1335. * Creates a `cargoQueue` object with the specified payload. Tasks added to the
  1336. * cargoQueue will be processed together (up to the `payload` limit) in `concurrency` parallel workers.
  1337. * If the all `workers` are in progress, the task is queued until one becomes available. Once
  1338. * a `worker` has completed some tasks, each callback of those tasks is
  1339. * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
  1340. * for how `cargo` and `queue` work.
  1341. *
  1342. * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
  1343. * at a time, and [`cargo`]{@link module:ControlFlow.cargo} passes an array of tasks to a single worker,
  1344. * the cargoQueue passes an array of tasks to multiple parallel workers.
  1345. *
  1346. * @name cargoQueue
  1347. * @static
  1348. * @memberOf module:ControlFlow
  1349. * @method
  1350. * @see [async.queue]{@link module:ControlFlow.queue}
  1351. * @see [async.cargo]{@link module:ControlFLow.cargo}
  1352. * @category Control Flow
  1353. * @param {AsyncFunction} worker - An asynchronous function for processing an array
  1354. * of queued tasks. Invoked with `(tasks, callback)`.
  1355. * @param {number} [concurrency=1] - An `integer` for determining how many
  1356. * `worker` functions should be run in parallel. If omitted, the concurrency
  1357. * defaults to `1`. If the concurrency is `0`, an error is thrown.
  1358. * @param {number} [payload=Infinity] - An optional `integer` for determining
  1359. * how many tasks should be processed per round; if omitted, the default is
  1360. * unlimited.
  1361. * @returns {module:ControlFlow.CargoObject} A cargoQueue object to manage the tasks. Callbacks can
  1362. * attached as certain properties to listen for specific events during the
  1363. * lifecycle of the cargoQueue and inner queue.
  1364. * @example
  1365. *
  1366. * // create a cargoQueue object with payload 2 and concurrency 2
  1367. * var cargoQueue = async.cargoQueue(function(tasks, callback) {
  1368. * for (var i=0; i<tasks.length; i++) {
  1369. * console.log('hello ' + tasks[i].name);
  1370. * }
  1371. * callback();
  1372. * }, 2, 2);
  1373. *
  1374. * // add some items
  1375. * cargoQueue.push({name: 'foo'}, function(err) {
  1376. * console.log('finished processing foo');
  1377. * });
  1378. * cargoQueue.push({name: 'bar'}, function(err) {
  1379. * console.log('finished processing bar');
  1380. * });
  1381. * cargoQueue.push({name: 'baz'}, function(err) {
  1382. * console.log('finished processing baz');
  1383. * });
  1384. * cargoQueue.push({name: 'boo'}, function(err) {
  1385. * console.log('finished processing boo');
  1386. * });
  1387. */
  1388. function cargo$1(worker, concurrency, payload) {
  1389. return queue(worker, concurrency, payload);
  1390. }
  1391. /**
  1392. * Reduces `coll` into a single value using an async `iteratee` to return each
  1393. * successive step. `memo` is the initial state of the reduction. This function
  1394. * only operates in series.
  1395. *
  1396. * For performance reasons, it may make sense to split a call to this function
  1397. * into a parallel map, and then use the normal `Array.prototype.reduce` on the
  1398. * results. This function is for situations where each step in the reduction
  1399. * needs to be async; if you can get the data before reducing it, then it's
  1400. * probably a good idea to do so.
  1401. *
  1402. * @name reduce
  1403. * @static
  1404. * @memberOf module:Collections
  1405. * @method
  1406. * @alias inject
  1407. * @alias foldl
  1408. * @category Collection
  1409. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  1410. * @param {*} memo - The initial state of the reduction.
  1411. * @param {AsyncFunction} iteratee - A function applied to each item in the
  1412. * array to produce the next step in the reduction.
  1413. * The `iteratee` should complete with the next state of the reduction.
  1414. * If the iteratee complete with an error, the reduction is stopped and the
  1415. * main `callback` is immediately called with the error.
  1416. * Invoked with (memo, item, callback).
  1417. * @param {Function} [callback] - A callback which is called after all the
  1418. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  1419. * (err, result).
  1420. * @returns {Promise} a promise, if no callback is passed
  1421. * @example
  1422. *
  1423. * async.reduce([1,2,3], 0, function(memo, item, callback) {
  1424. * // pointless async:
  1425. * process.nextTick(function() {
  1426. * callback(null, memo + item)
  1427. * });
  1428. * }, function(err, result) {
  1429. * // result is now equal to the last value of memo, which is 6
  1430. * });
  1431. */
  1432. function reduce(coll, memo, iteratee, callback) {
  1433. callback = once(callback);
  1434. var _iteratee = wrapAsync(iteratee);
  1435. return eachOfSeries$1(coll, (x, i, iterCb) => {
  1436. _iteratee(memo, x, (err, v) => {
  1437. memo = v;
  1438. iterCb(err);
  1439. });
  1440. }, err => callback(err, memo));
  1441. }
  1442. var reduce$1 = awaitify(reduce, 4);
  1443. /**
  1444. * Version of the compose function that is more natural to read. Each function
  1445. * consumes the return value of the previous function. It is the equivalent of
  1446. * [compose]{@link module:ControlFlow.compose} with the arguments reversed.
  1447. *
  1448. * Each function is executed with the `this` binding of the composed function.
  1449. *
  1450. * @name seq
  1451. * @static
  1452. * @memberOf module:ControlFlow
  1453. * @method
  1454. * @see [async.compose]{@link module:ControlFlow.compose}
  1455. * @category Control Flow
  1456. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  1457. * @returns {Function} a function that composes the `functions` in order
  1458. * @example
  1459. *
  1460. * // Requires lodash (or underscore), express3 and dresende's orm2.
  1461. * // Part of an app, that fetches cats of the logged user.
  1462. * // This example uses `seq` function to avoid overnesting and error
  1463. * // handling clutter.
  1464. * app.get('/cats', function(request, response) {
  1465. * var User = request.models.User;
  1466. * async.seq(
  1467. * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
  1468. * function(user, fn) {
  1469. * user.getCats(fn); // 'getCats' has signature (callback(err, data))
  1470. * }
  1471. * )(req.session.user_id, function (err, cats) {
  1472. * if (err) {
  1473. * console.error(err);
  1474. * response.json({ status: 'error', message: err.message });
  1475. * } else {
  1476. * response.json({ status: 'ok', message: 'Cats found', data: cats });
  1477. * }
  1478. * });
  1479. * });
  1480. */
  1481. function seq(...functions) {
  1482. var _functions = functions.map(wrapAsync);
  1483. return function (...args) {
  1484. var that = this;
  1485. var cb = args[args.length - 1];
  1486. if (typeof cb == 'function') {
  1487. args.pop();
  1488. } else {
  1489. cb = promiseCallback();
  1490. }
  1491. reduce$1(_functions, args, (newargs, fn, iterCb) => {
  1492. fn.apply(that, newargs.concat((err, ...nextargs) => {
  1493. iterCb(err, nextargs);
  1494. }));
  1495. },
  1496. (err, results) => cb(err, ...results));
  1497. return cb[PROMISE_SYMBOL]
  1498. };
  1499. }
  1500. /**
  1501. * Creates a function which is a composition of the passed asynchronous
  1502. * functions. Each function consumes the return value of the function that
  1503. * follows. Composing functions `f()`, `g()`, and `h()` would produce the result
  1504. * of `f(g(h()))`, only this version uses callbacks to obtain the return values.
  1505. *
  1506. * If the last argument to the composed function is not a function, a promise
  1507. * is returned when you call it.
  1508. *
  1509. * Each function is executed with the `this` binding of the composed function.
  1510. *
  1511. * @name compose
  1512. * @static
  1513. * @memberOf module:ControlFlow
  1514. * @method
  1515. * @category Control Flow
  1516. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  1517. * @returns {Function} an asynchronous function that is the composed
  1518. * asynchronous `functions`
  1519. * @example
  1520. *
  1521. * function add1(n, callback) {
  1522. * setTimeout(function () {
  1523. * callback(null, n + 1);
  1524. * }, 10);
  1525. * }
  1526. *
  1527. * function mul3(n, callback) {
  1528. * setTimeout(function () {
  1529. * callback(null, n * 3);
  1530. * }, 10);
  1531. * }
  1532. *
  1533. * var add1mul3 = async.compose(mul3, add1);
  1534. * add1mul3(4, function (err, result) {
  1535. * // result now equals 15
  1536. * });
  1537. */
  1538. function compose(...args) {
  1539. return seq(...args.reverse());
  1540. }
  1541. /**
  1542. * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.
  1543. *
  1544. * @name mapLimit
  1545. * @static
  1546. * @memberOf module:Collections
  1547. * @method
  1548. * @see [async.map]{@link module:Collections.map}
  1549. * @category Collection
  1550. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  1551. * @param {number} limit - The maximum number of async operations at a time.
  1552. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  1553. * `coll`.
  1554. * The iteratee should complete with the transformed item.
  1555. * Invoked with (item, callback).
  1556. * @param {Function} [callback] - A callback which is called when all `iteratee`
  1557. * functions have finished, or an error occurs. Results is an array of the
  1558. * transformed items from the `coll`. Invoked with (err, results).
  1559. * @returns {Promise} a promise, if no callback is passed
  1560. */
  1561. function mapLimit (coll, limit, iteratee, callback) {
  1562. return _asyncMap(eachOfLimit(limit), coll, iteratee, callback)
  1563. }
  1564. var mapLimit$1 = awaitify(mapLimit, 4);
  1565. /**
  1566. * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.
  1567. *
  1568. * @name concatLimit
  1569. * @static
  1570. * @memberOf module:Collections
  1571. * @method
  1572. * @see [async.concat]{@link module:Collections.concat}
  1573. * @category Collection
  1574. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  1575. * @param {number} limit - The maximum number of async operations at a time.
  1576. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  1577. * which should use an array as its result. Invoked with (item, callback).
  1578. * @param {Function} [callback] - A callback which is called after all the
  1579. * `iteratee` functions have finished, or an error occurs. Results is an array
  1580. * containing the concatenated results of the `iteratee` function. Invoked with
  1581. * (err, results).
  1582. * @returns A Promise, if no callback is passed
  1583. */
  1584. function concatLimit(coll, limit, iteratee, callback) {
  1585. var _iteratee = wrapAsync(iteratee);
  1586. return mapLimit$1(coll, limit, (val, iterCb) => {
  1587. _iteratee(val, (err, ...args) => {
  1588. if (err) return iterCb(err);
  1589. return iterCb(null, args);
  1590. });
  1591. }, (err, mapResults) => {
  1592. var result = [];
  1593. for (var i = 0; i < mapResults.length; i++) {
  1594. if (mapResults[i]) {
  1595. result = result.concat(...mapResults[i]);
  1596. }
  1597. }
  1598. return callback(err, result);
  1599. });
  1600. }
  1601. var concatLimit$1 = awaitify(concatLimit, 4);
  1602. /**
  1603. * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
  1604. * the concatenated list. The `iteratee`s are called in parallel, and the
  1605. * results are concatenated as they return. The results array will be returned in
  1606. * the original order of `coll` passed to the `iteratee` function.
  1607. *
  1608. * @name concat
  1609. * @static
  1610. * @memberOf module:Collections
  1611. * @method
  1612. * @category Collection
  1613. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  1614. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  1615. * which should use an array as its result. Invoked with (item, callback).
  1616. * @param {Function} [callback] - A callback which is called after all the
  1617. * `iteratee` functions have finished, or an error occurs. Results is an array
  1618. * containing the concatenated results of the `iteratee` function. Invoked with
  1619. * (err, results).
  1620. * @returns A Promise, if no callback is passed
  1621. * @example
  1622. *
  1623. * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
  1624. * // files is now a list of filenames that exist in the 3 directories
  1625. * });
  1626. */
  1627. function concat(coll, iteratee, callback) {
  1628. return concatLimit$1(coll, Infinity, iteratee, callback)
  1629. }
  1630. var concat$1 = awaitify(concat, 3);
  1631. /**
  1632. * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
  1633. *
  1634. * @name concatSeries
  1635. * @static
  1636. * @memberOf module:Collections
  1637. * @method
  1638. * @see [async.concat]{@link module:Collections.concat}
  1639. * @category Collection
  1640. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  1641. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.
  1642. * The iteratee should complete with an array an array of results.
  1643. * Invoked with (item, callback).
  1644. * @param {Function} [callback] - A callback which is called after all the
  1645. * `iteratee` functions have finished, or an error occurs. Results is an array
  1646. * containing the concatenated results of the `iteratee` function. Invoked with
  1647. * (err, results).
  1648. * @returns A Promise, if no callback is passed
  1649. */
  1650. function concatSeries(coll, iteratee, callback) {
  1651. return concatLimit$1(coll, 1, iteratee, callback)
  1652. }
  1653. var concatSeries$1 = awaitify(concatSeries, 3);
  1654. /**
  1655. * Returns a function that when called, calls-back with the values provided.
  1656. * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
  1657. * [`auto`]{@link module:ControlFlow.auto}.
  1658. *
  1659. * @name constant
  1660. * @static
  1661. * @memberOf module:Utils
  1662. * @method
  1663. * @category Util
  1664. * @param {...*} arguments... - Any number of arguments to automatically invoke
  1665. * callback with.
  1666. * @returns {AsyncFunction} Returns a function that when invoked, automatically
  1667. * invokes the callback with the previous given arguments.
  1668. * @example
  1669. *
  1670. * async.waterfall([
  1671. * async.constant(42),
  1672. * function (value, next) {
  1673. * // value === 42
  1674. * },
  1675. * //...
  1676. * ], callback);
  1677. *
  1678. * async.waterfall([
  1679. * async.constant(filename, "utf8"),
  1680. * fs.readFile,
  1681. * function (fileData, next) {
  1682. * //...
  1683. * }
  1684. * //...
  1685. * ], callback);
  1686. *
  1687. * async.auto({
  1688. * hostname: async.constant("https://server.net/"),
  1689. * port: findFreePort,
  1690. * launchServer: ["hostname", "port", function (options, cb) {
  1691. * startServer(options, cb);
  1692. * }],
  1693. * //...
  1694. * }, callback);
  1695. */
  1696. function constant(...args) {
  1697. return function (...ignoredArgs/*, callback*/) {
  1698. var callback = ignoredArgs.pop();
  1699. return callback(null, ...args);
  1700. };
  1701. }
  1702. function _createTester(check, getResult) {
  1703. return (eachfn, arr, _iteratee, cb) => {
  1704. var testPassed = false;
  1705. var testResult;
  1706. const iteratee = wrapAsync(_iteratee);
  1707. eachfn(arr, (value, _, callback) => {
  1708. iteratee(value, (err, result) => {
  1709. if (err) return callback(err)
  1710. if (check(result) && !testResult) {
  1711. testPassed = true;
  1712. testResult = getResult(true, value);
  1713. return callback(null, breakLoop);
  1714. }
  1715. callback();
  1716. });
  1717. }, err => {
  1718. if (err) return cb(err);
  1719. cb(null, testPassed ? testResult : getResult(false));
  1720. });
  1721. };
  1722. }
  1723. /**
  1724. * Returns the first value in `coll` that passes an async truth test. The
  1725. * `iteratee` is applied in parallel, meaning the first iteratee to return
  1726. * `true` will fire the detect `callback` with that result. That means the
  1727. * result might not be the first item in the original `coll` (in terms of order)
  1728. * that passes the test.
  1729. * If order within the original `coll` is important, then look at
  1730. * [`detectSeries`]{@link module:Collections.detectSeries}.
  1731. *
  1732. * @name detect
  1733. * @static
  1734. * @memberOf module:Collections
  1735. * @method
  1736. * @alias find
  1737. * @category Collections
  1738. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  1739. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  1740. * The iteratee must complete with a boolean value as its result.
  1741. * Invoked with (item, callback).
  1742. * @param {Function} [callback] - A callback which is called as soon as any
  1743. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  1744. * Result will be the first item in the array that passes the truth test
  1745. * (iteratee) or the value `undefined` if none passed. Invoked with
  1746. * (err, result).
  1747. * @returns A Promise, if no callback is passed
  1748. * @example
  1749. *
  1750. * async.detect(['file1','file2','file3'], function(filePath, callback) {
  1751. * fs.access(filePath, function(err) {
  1752. * callback(null, !err)
  1753. * });
  1754. * }, function(err, result) {
  1755. * // result now equals the first file in the list that exists
  1756. * });
  1757. */
  1758. function detect(coll, iteratee, callback) {
  1759. return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback)
  1760. }
  1761. var detect$1 = awaitify(detect, 3);
  1762. /**
  1763. * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
  1764. * time.
  1765. *
  1766. * @name detectLimit
  1767. * @static
  1768. * @memberOf module:Collections
  1769. * @method
  1770. * @see [async.detect]{@link module:Collections.detect}
  1771. * @alias findLimit
  1772. * @category Collections
  1773. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  1774. * @param {number} limit - The maximum number of async operations at a time.
  1775. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  1776. * The iteratee must complete with a boolean value as its result.
  1777. * Invoked with (item, callback).
  1778. * @param {Function} [callback] - A callback which is called as soon as any
  1779. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  1780. * Result will be the first item in the array that passes the truth test
  1781. * (iteratee) or the value `undefined` if none passed. Invoked with
  1782. * (err, result).
  1783. * @returns a Promise if no callback is passed
  1784. */
  1785. function detectLimit(coll, limit, iteratee, callback) {
  1786. return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback)
  1787. }
  1788. var detectLimit$1 = awaitify(detectLimit, 4);
  1789. /**
  1790. * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
  1791. *
  1792. * @name detectSeries
  1793. * @static
  1794. * @memberOf module:Collections
  1795. * @method
  1796. * @see [async.detect]{@link module:Collections.detect}
  1797. * @alias findSeries
  1798. * @category Collections
  1799. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  1800. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  1801. * The iteratee must complete with a boolean value as its result.
  1802. * Invoked with (item, callback).
  1803. * @param {Function} [callback] - A callback which is called as soon as any
  1804. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  1805. * Result will be the first item in the array that passes the truth test
  1806. * (iteratee) or the value `undefined` if none passed. Invoked with
  1807. * (err, result).
  1808. * @returns a Promise if no callback is passed
  1809. */
  1810. function detectSeries(coll, iteratee, callback) {
  1811. return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback)
  1812. }
  1813. var detectSeries$1 = awaitify(detectSeries, 3);
  1814. function consoleFunc(name) {
  1815. return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => {
  1816. if (typeof console === 'object') {
  1817. if (err) {
  1818. if (console.error) {
  1819. console.error(err);
  1820. }
  1821. } else if (console[name]) {
  1822. resultArgs.forEach(x => console[name](x));
  1823. }
  1824. }
  1825. })
  1826. }
  1827. /**
  1828. * Logs the result of an [`async` function]{@link AsyncFunction} to the
  1829. * `console` using `console.dir` to display the properties of the resulting object.
  1830. * Only works in Node.js or in browsers that support `console.dir` and
  1831. * `console.error` (such as FF and Chrome).
  1832. * If multiple arguments are returned from the async function,
  1833. * `console.dir` is called on each argument in order.
  1834. *
  1835. * @name dir
  1836. * @static
  1837. * @memberOf module:Utils
  1838. * @method
  1839. * @category Util
  1840. * @param {AsyncFunction} function - The function you want to eventually apply
  1841. * all arguments to.
  1842. * @param {...*} arguments... - Any number of arguments to apply to the function.
  1843. * @example
  1844. *
  1845. * // in a module
  1846. * var hello = function(name, callback) {
  1847. * setTimeout(function() {
  1848. * callback(null, {hello: name});
  1849. * }, 1000);
  1850. * };
  1851. *
  1852. * // in the node repl
  1853. * node> async.dir(hello, 'world');
  1854. * {hello: 'world'}
  1855. */
  1856. var dir = consoleFunc('dir');
  1857. /**
  1858. * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
  1859. * the order of operations, the arguments `test` and `iteratee` are switched.
  1860. *
  1861. * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
  1862. *
  1863. * @name doWhilst
  1864. * @static
  1865. * @memberOf module:ControlFlow
  1866. * @method
  1867. * @see [async.whilst]{@link module:ControlFlow.whilst}
  1868. * @category Control Flow
  1869. * @param {AsyncFunction} iteratee - A function which is called each time `test`
  1870. * passes. Invoked with (callback).
  1871. * @param {AsyncFunction} test - asynchronous truth test to perform after each
  1872. * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the
  1873. * non-error args from the previous callback of `iteratee`.
  1874. * @param {Function} [callback] - A callback which is called after the test
  1875. * function has failed and repeated execution of `iteratee` has stopped.
  1876. * `callback` will be passed an error and any arguments passed to the final
  1877. * `iteratee`'s callback. Invoked with (err, [results]);
  1878. * @returns {Promise} a promise, if no callback is passed
  1879. */
  1880. function doWhilst(iteratee, test, callback) {
  1881. callback = onlyOnce(callback);
  1882. var _fn = wrapAsync(iteratee);
  1883. var _test = wrapAsync(test);
  1884. var results;
  1885. function next(err, ...args) {
  1886. if (err) return callback(err);
  1887. if (err === false) return;
  1888. results = args;
  1889. _test(...args, check);
  1890. }
  1891. function check(err, truth) {
  1892. if (err) return callback(err);
  1893. if (err === false) return;
  1894. if (!truth) return callback(null, ...results);
  1895. _fn(next);
  1896. }
  1897. return check(null, true);
  1898. }
  1899. var doWhilst$1 = awaitify(doWhilst, 3);
  1900. /**
  1901. * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the
  1902. * argument ordering differs from `until`.
  1903. *
  1904. * @name doUntil
  1905. * @static
  1906. * @memberOf module:ControlFlow
  1907. * @method
  1908. * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}
  1909. * @category Control Flow
  1910. * @param {AsyncFunction} iteratee - An async function which is called each time
  1911. * `test` fails. Invoked with (callback).
  1912. * @param {AsyncFunction} test - asynchronous truth test to perform after each
  1913. * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the
  1914. * non-error args from the previous callback of `iteratee`
  1915. * @param {Function} [callback] - A callback which is called after the test
  1916. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  1917. * will be passed an error and any arguments passed to the final `iteratee`'s
  1918. * callback. Invoked with (err, [results]);
  1919. * @returns {Promise} a promise, if no callback is passed
  1920. */
  1921. function doUntil(iteratee, test, callback) {
  1922. const _test = wrapAsync(test);
  1923. return doWhilst$1(iteratee, (...args) => {
  1924. const cb = args.pop();
  1925. _test(...args, (err, truth) => cb (err, !truth));
  1926. }, callback);
  1927. }
  1928. function _withoutIndex(iteratee) {
  1929. return (value, index, callback) => iteratee(value, callback);
  1930. }
  1931. /**
  1932. * Applies the function `iteratee` to each item in `coll`, in parallel.
  1933. * The `iteratee` is called with an item from the list, and a callback for when
  1934. * it has finished. If the `iteratee` passes an error to its `callback`, the
  1935. * main `callback` (for the `each` function) is immediately called with the
  1936. * error.
  1937. *
  1938. * Note, that since this function applies `iteratee` to each item in parallel,
  1939. * there is no guarantee that the iteratee functions will complete in order.
  1940. *
  1941. * @name each
  1942. * @static
  1943. * @memberOf module:Collections
  1944. * @method
  1945. * @alias forEach
  1946. * @category Collection
  1947. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  1948. * @param {AsyncFunction} iteratee - An async function to apply to
  1949. * each item in `coll`. Invoked with (item, callback).
  1950. * The array index is not passed to the iteratee.
  1951. * If you need the index, use `eachOf`.
  1952. * @param {Function} [callback] - A callback which is called when all
  1953. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  1954. * @returns {Promise} a promise, if a callback is omitted
  1955. * @example
  1956. *
  1957. * // assuming openFiles is an array of file names and saveFile is a function
  1958. * // to save the modified contents of that file:
  1959. *
  1960. * async.each(openFiles, saveFile, function(err){
  1961. * // if any of the saves produced an error, err would equal that error
  1962. * });
  1963. *
  1964. * // assuming openFiles is an array of file names
  1965. * async.each(openFiles, function(file, callback) {
  1966. *
  1967. * // Perform operation on file here.
  1968. * console.log('Processing file ' + file);
  1969. *
  1970. * if( file.length > 32 ) {
  1971. * console.log('This file name is too long');
  1972. * callback('File name too long');
  1973. * } else {
  1974. * // Do work to process file here
  1975. * console.log('File processed');
  1976. * callback();
  1977. * }
  1978. * }, function(err) {
  1979. * // if any of the file processing produced an error, err would equal that error
  1980. * if( err ) {
  1981. * // One of the iterations produced an error.
  1982. * // All processing will now stop.
  1983. * console.log('A file failed to process');
  1984. * } else {
  1985. * console.log('All files have been processed successfully');
  1986. * }
  1987. * });
  1988. */
  1989. function eachLimit(coll, iteratee, callback) {
  1990. return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  1991. }
  1992. var each = awaitify(eachLimit, 3);
  1993. /**
  1994. * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
  1995. *
  1996. * @name eachLimit
  1997. * @static
  1998. * @memberOf module:Collections
  1999. * @method
  2000. * @see [async.each]{@link module:Collections.each}
  2001. * @alias forEachLimit
  2002. * @category Collection
  2003. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  2004. * @param {number} limit - The maximum number of async operations at a time.
  2005. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  2006. * `coll`.
  2007. * The array index is not passed to the iteratee.
  2008. * If you need the index, use `eachOfLimit`.
  2009. * Invoked with (item, callback).
  2010. * @param {Function} [callback] - A callback which is called when all
  2011. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  2012. * @returns {Promise} a promise, if a callback is omitted
  2013. */
  2014. function eachLimit$1(coll, limit, iteratee, callback) {
  2015. return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  2016. }
  2017. var eachLimit$2 = awaitify(eachLimit$1, 4);
  2018. /**
  2019. * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
  2020. *
  2021. * @name eachSeries
  2022. * @static
  2023. * @memberOf module:Collections
  2024. * @method
  2025. * @see [async.each]{@link module:Collections.each}
  2026. * @alias forEachSeries
  2027. * @category Collection
  2028. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  2029. * @param {AsyncFunction} iteratee - An async function to apply to each
  2030. * item in `coll`.
  2031. * The array index is not passed to the iteratee.
  2032. * If you need the index, use `eachOfSeries`.
  2033. * Invoked with (item, callback).
  2034. * @param {Function} [callback] - A callback which is called when all
  2035. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  2036. * @returns {Promise} a promise, if a callback is omitted
  2037. */
  2038. function eachSeries(coll, iteratee, callback) {
  2039. return eachLimit$2(coll, 1, iteratee, callback)
  2040. }
  2041. var eachSeries$1 = awaitify(eachSeries, 3);
  2042. /**
  2043. * Wrap an async function and ensure it calls its callback on a later tick of
  2044. * the event loop. If the function already calls its callback on a next tick,
  2045. * no extra deferral is added. This is useful for preventing stack overflows
  2046. * (`RangeError: Maximum call stack size exceeded`) and generally keeping
  2047. * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
  2048. * contained. ES2017 `async` functions are returned as-is -- they are immune
  2049. * to Zalgo's corrupting influences, as they always resolve on a later tick.
  2050. *
  2051. * @name ensureAsync
  2052. * @static
  2053. * @memberOf module:Utils
  2054. * @method
  2055. * @category Util
  2056. * @param {AsyncFunction} fn - an async function, one that expects a node-style
  2057. * callback as its last argument.
  2058. * @returns {AsyncFunction} Returns a wrapped function with the exact same call
  2059. * signature as the function passed in.
  2060. * @example
  2061. *
  2062. * function sometimesAsync(arg, callback) {
  2063. * if (cache[arg]) {
  2064. * return callback(null, cache[arg]); // this would be synchronous!!
  2065. * } else {
  2066. * doSomeIO(arg, callback); // this IO would be asynchronous
  2067. * }
  2068. * }
  2069. *
  2070. * // this has a risk of stack overflows if many results are cached in a row
  2071. * async.mapSeries(args, sometimesAsync, done);
  2072. *
  2073. * // this will defer sometimesAsync's callback if necessary,
  2074. * // preventing stack overflows
  2075. * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
  2076. */
  2077. function ensureAsync(fn) {
  2078. if (isAsync(fn)) return fn;
  2079. return function (...args/*, callback*/) {
  2080. var callback = args.pop();
  2081. var sync = true;
  2082. args.push((...innerArgs) => {
  2083. if (sync) {
  2084. setImmediate$1(() => callback(...innerArgs));
  2085. } else {
  2086. callback(...innerArgs);
  2087. }
  2088. });
  2089. fn.apply(this, args);
  2090. sync = false;
  2091. };
  2092. }
  2093. /**
  2094. * Returns `true` if every element in `coll` satisfies an async test. If any
  2095. * iteratee call returns `false`, the main `callback` is immediately called.
  2096. *
  2097. * @name every
  2098. * @static
  2099. * @memberOf module:Collections
  2100. * @method
  2101. * @alias all
  2102. * @category Collection
  2103. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  2104. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  2105. * in the collection in parallel.
  2106. * The iteratee must complete with a boolean result value.
  2107. * Invoked with (item, callback).
  2108. * @param {Function} [callback] - A callback which is called after all the
  2109. * `iteratee` functions have finished. Result will be either `true` or `false`
  2110. * depending on the values of the async tests. Invoked with (err, result).
  2111. * @returns {Promise} a promise, if no callback provided
  2112. * @example
  2113. *
  2114. * async.every(['file1','file2','file3'], function(filePath, callback) {
  2115. * fs.access(filePath, function(err) {
  2116. * callback(null, !err)
  2117. * });
  2118. * }, function(err, result) {
  2119. * // if result is true then every file exists
  2120. * });
  2121. */
  2122. function every(coll, iteratee, callback) {
  2123. return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback)
  2124. }
  2125. var every$1 = awaitify(every, 3);
  2126. /**
  2127. * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
  2128. *
  2129. * @name everyLimit
  2130. * @static
  2131. * @memberOf module:Collections
  2132. * @method
  2133. * @see [async.every]{@link module:Collections.every}
  2134. * @alias allLimit
  2135. * @category Collection
  2136. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  2137. * @param {number} limit - The maximum number of async operations at a time.
  2138. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  2139. * in the collection in parallel.
  2140. * The iteratee must complete with a boolean result value.
  2141. * Invoked with (item, callback).
  2142. * @param {Function} [callback] - A callback which is called after all the
  2143. * `iteratee` functions have finished. Result will be either `true` or `false`
  2144. * depending on the values of the async tests. Invoked with (err, result).
  2145. * @returns {Promise} a promise, if no callback provided
  2146. */
  2147. function everyLimit(coll, limit, iteratee, callback) {
  2148. return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback)
  2149. }
  2150. var everyLimit$1 = awaitify(everyLimit, 4);
  2151. /**
  2152. * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
  2153. *
  2154. * @name everySeries
  2155. * @static
  2156. * @memberOf module:Collections
  2157. * @method
  2158. * @see [async.every]{@link module:Collections.every}
  2159. * @alias allSeries
  2160. * @category Collection
  2161. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  2162. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  2163. * in the collection in series.
  2164. * The iteratee must complete with a boolean result value.
  2165. * Invoked with (item, callback).
  2166. * @param {Function} [callback] - A callback which is called after all the
  2167. * `iteratee` functions have finished. Result will be either `true` or `false`
  2168. * depending on the values of the async tests. Invoked with (err, result).
  2169. * @returns {Promise} a promise, if no callback provided
  2170. */
  2171. function everySeries(coll, iteratee, callback) {
  2172. return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback)
  2173. }
  2174. var everySeries$1 = awaitify(everySeries, 3);
  2175. function filterArray(eachfn, arr, iteratee, callback) {
  2176. var truthValues = new Array(arr.length);
  2177. eachfn(arr, (x, index, iterCb) => {
  2178. iteratee(x, (err, v) => {
  2179. truthValues[index] = !!v;
  2180. iterCb(err);
  2181. });
  2182. }, err => {
  2183. if (err) return callback(err);
  2184. var results = [];
  2185. for (var i = 0; i < arr.length; i++) {
  2186. if (truthValues[i]) results.push(arr[i]);
  2187. }
  2188. callback(null, results);
  2189. });
  2190. }
  2191. function filterGeneric(eachfn, coll, iteratee, callback) {
  2192. var results = [];
  2193. eachfn(coll, (x, index, iterCb) => {
  2194. iteratee(x, (err, v) => {
  2195. if (err) return iterCb(err);
  2196. if (v) {
  2197. results.push({index, value: x});
  2198. }
  2199. iterCb();
  2200. });
  2201. }, err => {
  2202. if (err) return callback(err);
  2203. callback(null, results
  2204. .sort((a, b) => a.index - b.index)
  2205. .map(v => v.value));
  2206. });
  2207. }
  2208. function _filter(eachfn, coll, iteratee, callback) {
  2209. var filter = isArrayLike(coll) ? filterArray : filterGeneric;
  2210. return filter(eachfn, coll, wrapAsync(iteratee), callback);
  2211. }
  2212. /**
  2213. * Returns a new array of all the values in `coll` which pass an async truth
  2214. * test. This operation is performed in parallel, but the results array will be
  2215. * in the same order as the original.
  2216. *
  2217. * @name filter
  2218. * @static
  2219. * @memberOf module:Collections
  2220. * @method
  2221. * @alias select
  2222. * @category Collection
  2223. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  2224. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  2225. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  2226. * with a boolean argument once it has completed. Invoked with (item, callback).
  2227. * @param {Function} [callback] - A callback which is called after all the
  2228. * `iteratee` functions have finished. Invoked with (err, results).
  2229. * @returns {Promise} a promise, if no callback provided
  2230. * @example
  2231. *
  2232. * async.filter(['file1','file2','file3'], function(filePath, callback) {
  2233. * fs.access(filePath, function(err) {
  2234. * callback(null, !err)
  2235. * });
  2236. * }, function(err, results) {
  2237. * // results now equals an array of the existing files
  2238. * });
  2239. */
  2240. function filter (coll, iteratee, callback) {
  2241. return _filter(eachOf$1, coll, iteratee, callback)
  2242. }
  2243. var filter$1 = awaitify(filter, 3);
  2244. /**
  2245. * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
  2246. * time.
  2247. *
  2248. * @name filterLimit
  2249. * @static
  2250. * @memberOf module:Collections
  2251. * @method
  2252. * @see [async.filter]{@link module:Collections.filter}
  2253. * @alias selectLimit
  2254. * @category Collection
  2255. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  2256. * @param {number} limit - The maximum number of async operations at a time.
  2257. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  2258. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  2259. * with a boolean argument once it has completed. Invoked with (item, callback).
  2260. * @param {Function} [callback] - A callback which is called after all the
  2261. * `iteratee` functions have finished. Invoked with (err, results).
  2262. * @returns {Promise} a promise, if no callback provided
  2263. */
  2264. function filterLimit (coll, limit, iteratee, callback) {
  2265. return _filter(eachOfLimit(limit), coll, iteratee, callback)
  2266. }
  2267. var filterLimit$1 = awaitify(filterLimit, 4);
  2268. /**
  2269. * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
  2270. *
  2271. * @name filterSeries
  2272. * @static
  2273. * @memberOf module:Collections
  2274. * @method
  2275. * @see [async.filter]{@link module:Collections.filter}
  2276. * @alias selectSeries
  2277. * @category Collection
  2278. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  2279. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  2280. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  2281. * with a boolean argument once it has completed. Invoked with (item, callback).
  2282. * @param {Function} [callback] - A callback which is called after all the
  2283. * `iteratee` functions have finished. Invoked with (err, results)
  2284. * @returns {Promise} a promise, if no callback provided
  2285. */
  2286. function filterSeries (coll, iteratee, callback) {
  2287. return _filter(eachOfSeries$1, coll, iteratee, callback)
  2288. }
  2289. var filterSeries$1 = awaitify(filterSeries, 3);
  2290. /**
  2291. * Calls the asynchronous function `fn` with a callback parameter that allows it
  2292. * to call itself again, in series, indefinitely.
  2293. * If an error is passed to the callback then `errback` is called with the
  2294. * error, and execution stops, otherwise it will never be called.
  2295. *
  2296. * @name forever
  2297. * @static
  2298. * @memberOf module:ControlFlow
  2299. * @method
  2300. * @category Control Flow
  2301. * @param {AsyncFunction} fn - an async function to call repeatedly.
  2302. * Invoked with (next).
  2303. * @param {Function} [errback] - when `fn` passes an error to it's callback,
  2304. * this function will be called, and execution stops. Invoked with (err).
  2305. * @returns {Promise} a promise that rejects if an error occurs and an errback
  2306. * is not passed
  2307. * @example
  2308. *
  2309. * async.forever(
  2310. * function(next) {
  2311. * // next is suitable for passing to things that need a callback(err [, whatever]);
  2312. * // it will result in this function being called again.
  2313. * },
  2314. * function(err) {
  2315. * // if next is called with a value in its first parameter, it will appear
  2316. * // in here as 'err', and execution will stop.
  2317. * }
  2318. * );
  2319. */
  2320. function forever(fn, errback) {
  2321. var done = onlyOnce(errback);
  2322. var task = wrapAsync(ensureAsync(fn));
  2323. function next(err) {
  2324. if (err) return done(err);
  2325. if (err === false) return;
  2326. task(next);
  2327. }
  2328. return next();
  2329. }
  2330. var forever$1 = awaitify(forever, 2);
  2331. /**
  2332. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.
  2333. *
  2334. * @name groupByLimit
  2335. * @static
  2336. * @memberOf module:Collections
  2337. * @method
  2338. * @see [async.groupBy]{@link module:Collections.groupBy}
  2339. * @category Collection
  2340. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  2341. * @param {number} limit - The maximum number of async operations at a time.
  2342. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  2343. * `coll`.
  2344. * The iteratee should complete with a `key` to group the value under.
  2345. * Invoked with (value, callback).
  2346. * @param {Function} [callback] - A callback which is called when all `iteratee`
  2347. * functions have finished, or an error occurs. Result is an `Object` whoses
  2348. * properties are arrays of values which returned the corresponding key.
  2349. * @returns {Promise} a promise, if no callback is passed
  2350. */
  2351. function groupByLimit(coll, limit, iteratee, callback) {
  2352. var _iteratee = wrapAsync(iteratee);
  2353. return mapLimit$1(coll, limit, (val, iterCb) => {
  2354. _iteratee(val, (err, key) => {
  2355. if (err) return iterCb(err);
  2356. return iterCb(null, {key, val});
  2357. });
  2358. }, (err, mapResults) => {
  2359. var result = {};
  2360. // from MDN, handle object having an `hasOwnProperty` prop
  2361. var {hasOwnProperty} = Object.prototype;
  2362. for (var i = 0; i < mapResults.length; i++) {
  2363. if (mapResults[i]) {
  2364. var {key} = mapResults[i];
  2365. var {val} = mapResults[i];
  2366. if (hasOwnProperty.call(result, key)) {
  2367. result[key].push(val);
  2368. } else {
  2369. result[key] = [val];
  2370. }
  2371. }
  2372. }
  2373. return callback(err, result);
  2374. });
  2375. }
  2376. var groupByLimit$1 = awaitify(groupByLimit, 4);
  2377. /**
  2378. * Returns a new object, where each value corresponds to an array of items, from
  2379. * `coll`, that returned the corresponding key. That is, the keys of the object
  2380. * correspond to the values passed to the `iteratee` callback.
  2381. *
  2382. * Note: Since this function applies the `iteratee` to each item in parallel,
  2383. * there is no guarantee that the `iteratee` functions will complete in order.
  2384. * However, the values for each key in the `result` will be in the same order as
  2385. * the original `coll`. For Objects, the values will roughly be in the order of
  2386. * the original Objects' keys (but this can vary across JavaScript engines).
  2387. *
  2388. * @name groupBy
  2389. * @static
  2390. * @memberOf module:Collections
  2391. * @method
  2392. * @category Collection
  2393. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  2394. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  2395. * `coll`.
  2396. * The iteratee should complete with a `key` to group the value under.
  2397. * Invoked with (value, callback).
  2398. * @param {Function} [callback] - A callback which is called when all `iteratee`
  2399. * functions have finished, or an error occurs. Result is an `Object` whoses
  2400. * properties are arrays of values which returned the corresponding key.
  2401. * @returns {Promise} a promise, if no callback is passed
  2402. * @example
  2403. *
  2404. * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) {
  2405. * db.findById(userId, function(err, user) {
  2406. * if (err) return callback(err);
  2407. * return callback(null, user.age);
  2408. * });
  2409. * }, function(err, result) {
  2410. * // result is object containing the userIds grouped by age
  2411. * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']};
  2412. * });
  2413. */
  2414. function groupBy (coll, iteratee, callback) {
  2415. return groupByLimit$1(coll, Infinity, iteratee, callback)
  2416. }
  2417. /**
  2418. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.
  2419. *
  2420. * @name groupBySeries
  2421. * @static
  2422. * @memberOf module:Collections
  2423. * @method
  2424. * @see [async.groupBy]{@link module:Collections.groupBy}
  2425. * @category Collection
  2426. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  2427. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  2428. * `coll`.
  2429. * The iteratee should complete with a `key` to group the value under.
  2430. * Invoked with (value, callback).
  2431. * @param {Function} [callback] - A callback which is called when all `iteratee`
  2432. * functions have finished, or an error occurs. Result is an `Object` whoses
  2433. * properties are arrays of values which returned the corresponding key.
  2434. * @returns {Promise} a promise, if no callback is passed
  2435. */
  2436. function groupBySeries (coll, iteratee, callback) {
  2437. return groupByLimit$1(coll, 1, iteratee, callback)
  2438. }
  2439. /**
  2440. * Logs the result of an `async` function to the `console`. Only works in
  2441. * Node.js or in browsers that support `console.log` and `console.error` (such
  2442. * as FF and Chrome). If multiple arguments are returned from the async
  2443. * function, `console.log` is called on each argument in order.
  2444. *
  2445. * @name log
  2446. * @static
  2447. * @memberOf module:Utils
  2448. * @method
  2449. * @category Util
  2450. * @param {AsyncFunction} function - The function you want to eventually apply
  2451. * all arguments to.
  2452. * @param {...*} arguments... - Any number of arguments to apply to the function.
  2453. * @example
  2454. *
  2455. * // in a module
  2456. * var hello = function(name, callback) {
  2457. * setTimeout(function() {
  2458. * callback(null, 'hello ' + name);
  2459. * }, 1000);
  2460. * };
  2461. *
  2462. * // in the node repl
  2463. * node> async.log(hello, 'world');
  2464. * 'hello world'
  2465. */
  2466. var log = consoleFunc('log');
  2467. /**
  2468. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
  2469. * time.
  2470. *
  2471. * @name mapValuesLimit
  2472. * @static
  2473. * @memberOf module:Collections
  2474. * @method
  2475. * @see [async.mapValues]{@link module:Collections.mapValues}
  2476. * @category Collection
  2477. * @param {Object} obj - A collection to iterate over.
  2478. * @param {number} limit - The maximum number of async operations at a time.
  2479. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  2480. * in `coll`.
  2481. * The iteratee should complete with the transformed value as its result.
  2482. * Invoked with (value, key, callback).
  2483. * @param {Function} [callback] - A callback which is called when all `iteratee`
  2484. * functions have finished, or an error occurs. `result` is a new object consisting
  2485. * of each key from `obj`, with each transformed value on the right-hand side.
  2486. * Invoked with (err, result).
  2487. * @returns {Promise} a promise, if no callback is passed
  2488. */
  2489. function mapValuesLimit(obj, limit, iteratee, callback) {
  2490. callback = once(callback);
  2491. var newObj = {};
  2492. var _iteratee = wrapAsync(iteratee);
  2493. return eachOfLimit(limit)(obj, (val, key, next) => {
  2494. _iteratee(val, key, (err, result) => {
  2495. if (err) return next(err);
  2496. newObj[key] = result;
  2497. next();
  2498. });
  2499. }, err => callback(err, newObj));
  2500. }
  2501. var mapValuesLimit$1 = awaitify(mapValuesLimit, 4);
  2502. /**
  2503. * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.
  2504. *
  2505. * Produces a new Object by mapping each value of `obj` through the `iteratee`
  2506. * function. The `iteratee` is called each `value` and `key` from `obj` and a
  2507. * callback for when it has finished processing. Each of these callbacks takes
  2508. * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`
  2509. * passes an error to its callback, the main `callback` (for the `mapValues`
  2510. * function) is immediately called with the error.
  2511. *
  2512. * Note, the order of the keys in the result is not guaranteed. The keys will
  2513. * be roughly in the order they complete, (but this is very engine-specific)
  2514. *
  2515. * @name mapValues
  2516. * @static
  2517. * @memberOf module:Collections
  2518. * @method
  2519. * @category Collection
  2520. * @param {Object} obj - A collection to iterate over.
  2521. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  2522. * in `coll`.
  2523. * The iteratee should complete with the transformed value as its result.
  2524. * Invoked with (value, key, callback).
  2525. * @param {Function} [callback] - A callback which is called when all `iteratee`
  2526. * functions have finished, or an error occurs. `result` is a new object consisting
  2527. * of each key from `obj`, with each transformed value on the right-hand side.
  2528. * Invoked with (err, result).
  2529. * @returns {Promise} a promise, if no callback is passed
  2530. * @example
  2531. *
  2532. * async.mapValues({
  2533. * f1: 'file1',
  2534. * f2: 'file2',
  2535. * f3: 'file3'
  2536. * }, function (file, key, callback) {
  2537. * fs.stat(file, callback);
  2538. * }, function(err, result) {
  2539. * // result is now a map of stats for each file, e.g.
  2540. * // {
  2541. * // f1: [stats for file1],
  2542. * // f2: [stats for file2],
  2543. * // f3: [stats for file3]
  2544. * // }
  2545. * });
  2546. */
  2547. function mapValues(obj, iteratee, callback) {
  2548. return mapValuesLimit$1(obj, Infinity, iteratee, callback)
  2549. }
  2550. /**
  2551. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.
  2552. *
  2553. * @name mapValuesSeries
  2554. * @static
  2555. * @memberOf module:Collections
  2556. * @method
  2557. * @see [async.mapValues]{@link module:Collections.mapValues}
  2558. * @category Collection
  2559. * @param {Object} obj - A collection to iterate over.
  2560. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  2561. * in `coll`.
  2562. * The iteratee should complete with the transformed value as its result.
  2563. * Invoked with (value, key, callback).
  2564. * @param {Function} [callback] - A callback which is called when all `iteratee`
  2565. * functions have finished, or an error occurs. `result` is a new object consisting
  2566. * of each key from `obj`, with each transformed value on the right-hand side.
  2567. * Invoked with (err, result).
  2568. * @returns {Promise} a promise, if no callback is passed
  2569. */
  2570. function mapValuesSeries(obj, iteratee, callback) {
  2571. return mapValuesLimit$1(obj, 1, iteratee, callback)
  2572. }
  2573. /**
  2574. * Caches the results of an async function. When creating a hash to store
  2575. * function results against, the callback is omitted from the hash and an
  2576. * optional hash function can be used.
  2577. *
  2578. * **Note: if the async function errs, the result will not be cached and
  2579. * subsequent calls will call the wrapped function.**
  2580. *
  2581. * If no hash function is specified, the first argument is used as a hash key,
  2582. * which may work reasonably if it is a string or a data type that converts to a
  2583. * distinct string. Note that objects and arrays will not behave reasonably.
  2584. * Neither will cases where the other arguments are significant. In such cases,
  2585. * specify your own hash function.
  2586. *
  2587. * The cache of results is exposed as the `memo` property of the function
  2588. * returned by `memoize`.
  2589. *
  2590. * @name memoize
  2591. * @static
  2592. * @memberOf module:Utils
  2593. * @method
  2594. * @category Util
  2595. * @param {AsyncFunction} fn - The async function to proxy and cache results from.
  2596. * @param {Function} hasher - An optional function for generating a custom hash
  2597. * for storing results. It has all the arguments applied to it apart from the
  2598. * callback, and must be synchronous.
  2599. * @returns {AsyncFunction} a memoized version of `fn`
  2600. * @example
  2601. *
  2602. * var slow_fn = function(name, callback) {
  2603. * // do something
  2604. * callback(null, result);
  2605. * };
  2606. * var fn = async.memoize(slow_fn);
  2607. *
  2608. * // fn can now be used as if it were slow_fn
  2609. * fn('some name', function() {
  2610. * // callback
  2611. * });
  2612. */
  2613. function memoize(fn, hasher = v => v) {
  2614. var memo = Object.create(null);
  2615. var queues = Object.create(null);
  2616. var _fn = wrapAsync(fn);
  2617. var memoized = initialParams((args, callback) => {
  2618. var key = hasher(...args);
  2619. if (key in memo) {
  2620. setImmediate$1(() => callback(null, ...memo[key]));
  2621. } else if (key in queues) {
  2622. queues[key].push(callback);
  2623. } else {
  2624. queues[key] = [callback];
  2625. _fn(...args, (err, ...resultArgs) => {
  2626. // #1465 don't memoize if an error occurred
  2627. if (!err) {
  2628. memo[key] = resultArgs;
  2629. }
  2630. var q = queues[key];
  2631. delete queues[key];
  2632. for (var i = 0, l = q.length; i < l; i++) {
  2633. q[i](err, ...resultArgs);
  2634. }
  2635. });
  2636. }
  2637. });
  2638. memoized.memo = memo;
  2639. memoized.unmemoized = fn;
  2640. return memoized;
  2641. }
  2642. /**
  2643. * Calls `callback` on a later loop around the event loop. In Node.js this just
  2644. * calls `process.nextTick`. In the browser it will use `setImmediate` if
  2645. * available, otherwise `setTimeout(callback, 0)`, which means other higher
  2646. * priority events may precede the execution of `callback`.
  2647. *
  2648. * This is used internally for browser-compatibility purposes.
  2649. *
  2650. * @name nextTick
  2651. * @static
  2652. * @memberOf module:Utils
  2653. * @method
  2654. * @see [async.setImmediate]{@link module:Utils.setImmediate}
  2655. * @category Util
  2656. * @param {Function} callback - The function to call on a later loop around
  2657. * the event loop. Invoked with (args...).
  2658. * @param {...*} args... - any number of additional arguments to pass to the
  2659. * callback on the next tick.
  2660. * @example
  2661. *
  2662. * var call_order = [];
  2663. * async.nextTick(function() {
  2664. * call_order.push('two');
  2665. * // call_order now equals ['one','two']
  2666. * });
  2667. * call_order.push('one');
  2668. *
  2669. * async.setImmediate(function (a, b, c) {
  2670. * // a, b, and c equal 1, 2, and 3
  2671. * }, 1, 2, 3);
  2672. */
  2673. var _defer$1;
  2674. if (hasNextTick) {
  2675. _defer$1 = process.nextTick;
  2676. } else if (hasSetImmediate) {
  2677. _defer$1 = setImmediate;
  2678. } else {
  2679. _defer$1 = fallback;
  2680. }
  2681. var nextTick = wrap(_defer$1);
  2682. var _parallel = awaitify((eachfn, tasks, callback) => {
  2683. var results = isArrayLike(tasks) ? [] : {};
  2684. eachfn(tasks, (task, key, taskCb) => {
  2685. wrapAsync(task)((err, ...result) => {
  2686. if (result.length < 2) {
  2687. [result] = result;
  2688. }
  2689. results[key] = result;
  2690. taskCb(err);
  2691. });
  2692. }, err => callback(err, results));
  2693. }, 3);
  2694. /**
  2695. * Run the `tasks` collection of functions in parallel, without waiting until
  2696. * the previous function has completed. If any of the functions pass an error to
  2697. * its callback, the main `callback` is immediately called with the value of the
  2698. * error. Once the `tasks` have completed, the results are passed to the final
  2699. * `callback` as an array.
  2700. *
  2701. * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about
  2702. * parallel execution of code. If your tasks do not use any timers or perform
  2703. * any I/O, they will actually be executed in series. Any synchronous setup
  2704. * sections for each task will happen one after the other. JavaScript remains
  2705. * single-threaded.
  2706. *
  2707. * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the
  2708. * execution of other tasks when a task fails.
  2709. *
  2710. * It is also possible to use an object instead of an array. Each property will
  2711. * be run as a function and the results will be passed to the final `callback`
  2712. * as an object instead of an array. This can be a more readable way of handling
  2713. * results from {@link async.parallel}.
  2714. *
  2715. * @name parallel
  2716. * @static
  2717. * @memberOf module:ControlFlow
  2718. * @method
  2719. * @category Control Flow
  2720. * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of
  2721. * [async functions]{@link AsyncFunction} to run.
  2722. * Each async function can complete with any number of optional `result` values.
  2723. * @param {Function} [callback] - An optional callback to run once all the
  2724. * functions have completed successfully. This function gets a results array
  2725. * (or object) containing all the result arguments passed to the task callbacks.
  2726. * Invoked with (err, results).
  2727. * @returns {Promise} a promise, if a callback is not passed
  2728. *
  2729. * @example
  2730. * async.parallel([
  2731. * function(callback) {
  2732. * setTimeout(function() {
  2733. * callback(null, 'one');
  2734. * }, 200);
  2735. * },
  2736. * function(callback) {
  2737. * setTimeout(function() {
  2738. * callback(null, 'two');
  2739. * }, 100);
  2740. * }
  2741. * ],
  2742. * // optional callback
  2743. * function(err, results) {
  2744. * // the results array will equal ['one','two'] even though
  2745. * // the second function had a shorter timeout.
  2746. * });
  2747. *
  2748. * // an example using an object instead of an array
  2749. * async.parallel({
  2750. * one: function(callback) {
  2751. * setTimeout(function() {
  2752. * callback(null, 1);
  2753. * }, 200);
  2754. * },
  2755. * two: function(callback) {
  2756. * setTimeout(function() {
  2757. * callback(null, 2);
  2758. * }, 100);
  2759. * }
  2760. * }, function(err, results) {
  2761. * // results is now equals to: {one: 1, two: 2}
  2762. * });
  2763. */
  2764. function parallel(tasks, callback) {
  2765. return _parallel(eachOf$1, tasks, callback);
  2766. }
  2767. /**
  2768. * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a
  2769. * time.
  2770. *
  2771. * @name parallelLimit
  2772. * @static
  2773. * @memberOf module:ControlFlow
  2774. * @method
  2775. * @see [async.parallel]{@link module:ControlFlow.parallel}
  2776. * @category Control Flow
  2777. * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of
  2778. * [async functions]{@link AsyncFunction} to run.
  2779. * Each async function can complete with any number of optional `result` values.
  2780. * @param {number} limit - The maximum number of async operations at a time.
  2781. * @param {Function} [callback] - An optional callback to run once all the
  2782. * functions have completed successfully. This function gets a results array
  2783. * (or object) containing all the result arguments passed to the task callbacks.
  2784. * Invoked with (err, results).
  2785. * @returns {Promise} a promise, if a callback is not passed
  2786. */
  2787. function parallelLimit(tasks, limit, callback) {
  2788. return _parallel(eachOfLimit(limit), tasks, callback);
  2789. }
  2790. /**
  2791. * A queue of tasks for the worker function to complete.
  2792. * @typedef {Iterable} QueueObject
  2793. * @memberOf module:ControlFlow
  2794. * @property {Function} length - a function returning the number of items
  2795. * waiting to be processed. Invoke with `queue.length()`.
  2796. * @property {boolean} started - a boolean indicating whether or not any
  2797. * items have been pushed and processed by the queue.
  2798. * @property {Function} running - a function returning the number of items
  2799. * currently being processed. Invoke with `queue.running()`.
  2800. * @property {Function} workersList - a function returning the array of items
  2801. * currently being processed. Invoke with `queue.workersList()`.
  2802. * @property {Function} idle - a function returning false if there are items
  2803. * waiting or being processed, or true if not. Invoke with `queue.idle()`.
  2804. * @property {number} concurrency - an integer for determining how many `worker`
  2805. * functions should be run in parallel. This property can be changed after a
  2806. * `queue` is created to alter the concurrency on-the-fly.
  2807. * @property {Function} push - add a new task to the `queue`. Calls `callback`
  2808. * once the `worker` has finished processing the task. Instead of a single task,
  2809. * a `tasks` array can be submitted. The respective callback is used for every
  2810. * task in the list. Invoke with `queue.push(task, [callback])`,
  2811. * @property {Function} unshift - add a new task to the front of the `queue`.
  2812. * Invoke with `queue.unshift(task, [callback])`.
  2813. * @property {Function} remove - remove items from the queue that match a test
  2814. * function. The test function will be passed an object with a `data` property,
  2815. * and a `priority` property, if this is a
  2816. * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
  2817. * Invoked with `queue.remove(testFn)`, where `testFn` is of the form
  2818. * `function ({data, priority}) {}` and returns a Boolean.
  2819. * @property {Function} saturated - a callback that is called when the number of
  2820. * running workers hits the `concurrency` limit, and further tasks will be
  2821. * queued.
  2822. * @property {Function} unsaturated - a callback that is called when the number
  2823. * of running workers is less than the `concurrency` & `buffer` limits, and
  2824. * further tasks will not be queued.
  2825. * @property {number} buffer - A minimum threshold buffer in order to say that
  2826. * the `queue` is `unsaturated`.
  2827. * @property {Function} empty - a callback that is called when the last item
  2828. * from the `queue` is given to a `worker`.
  2829. * @property {Function} drain - a callback that is called when the last item
  2830. * from the `queue` has returned from the `worker`.
  2831. * @property {Function} error - a callback that is called when a task errors.
  2832. * Has the signature `function(error, task)`.
  2833. * @property {boolean} paused - a boolean for determining whether the queue is
  2834. * in a paused state.
  2835. * @property {Function} pause - a function that pauses the processing of tasks
  2836. * until `resume()` is called. Invoke with `queue.pause()`.
  2837. * @property {Function} resume - a function that resumes the processing of
  2838. * queued tasks when the queue is paused. Invoke with `queue.resume()`.
  2839. * @property {Function} kill - a function that removes the `drain` callback and
  2840. * empties remaining tasks from the queue forcing it to go idle. No more tasks
  2841. * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
  2842. *
  2843. * @example
  2844. * const q = aync.queue(worker, 2)
  2845. * q.push(item1)
  2846. * q.push(item2)
  2847. * q.push(item3)
  2848. * // queues are iterable, spread into an array to inspect
  2849. * const items = [...q] // [item1, item2, item3]
  2850. * // or use for of
  2851. * for (let item of q) {
  2852. * console.log(item)
  2853. * }
  2854. */
  2855. /**
  2856. * Creates a `queue` object with the specified `concurrency`. Tasks added to the
  2857. * `queue` are processed in parallel (up to the `concurrency` limit). If all
  2858. * `worker`s are in progress, the task is queued until one becomes available.
  2859. * Once a `worker` completes a `task`, that `task`'s callback is called.
  2860. *
  2861. * @name queue
  2862. * @static
  2863. * @memberOf module:ControlFlow
  2864. * @method
  2865. * @category Control Flow
  2866. * @param {AsyncFunction} worker - An async function for processing a queued task.
  2867. * If you want to handle errors from an individual task, pass a callback to
  2868. * `q.push()`. Invoked with (task, callback).
  2869. * @param {number} [concurrency=1] - An `integer` for determining how many
  2870. * `worker` functions should be run in parallel. If omitted, the concurrency
  2871. * defaults to `1`. If the concurrency is `0`, an error is thrown.
  2872. * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be
  2873. * attached as certain properties to listen for specific events during the
  2874. * lifecycle of the queue.
  2875. * @example
  2876. *
  2877. * // create a queue object with concurrency 2
  2878. * var q = async.queue(function(task, callback) {
  2879. * console.log('hello ' + task.name);
  2880. * callback();
  2881. * }, 2);
  2882. *
  2883. * // assign a callback
  2884. * q.drain = function() {
  2885. * console.log('all items have been processed');
  2886. * };
  2887. *
  2888. * // assign an error callback
  2889. * q.error = function(err, task) {
  2890. * console.error('task experienced an error');
  2891. * };
  2892. *
  2893. * // add some items to the queue
  2894. * q.push({name: 'foo'}, function(err) {
  2895. * console.log('finished processing foo');
  2896. * });
  2897. * q.push({name: 'bar'}, function (err) {
  2898. * console.log('finished processing bar');
  2899. * });
  2900. *
  2901. * // add some items to the queue (batch-wise)
  2902. * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
  2903. * console.log('finished processing item');
  2904. * });
  2905. *
  2906. * // add some items to the front of the queue
  2907. * q.unshift({name: 'bar'}, function (err) {
  2908. * console.log('finished processing bar');
  2909. * });
  2910. */
  2911. function queue$1 (worker, concurrency) {
  2912. var _worker = wrapAsync(worker);
  2913. return queue((items, cb) => {
  2914. _worker(items[0], cb);
  2915. }, concurrency, 1);
  2916. }
  2917. /**
  2918. * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and
  2919. * completed in ascending priority order.
  2920. *
  2921. * @name priorityQueue
  2922. * @static
  2923. * @memberOf module:ControlFlow
  2924. * @method
  2925. * @see [async.queue]{@link module:ControlFlow.queue}
  2926. * @category Control Flow
  2927. * @param {AsyncFunction} worker - An async function for processing a queued task.
  2928. * If you want to handle errors from an individual task, pass a callback to
  2929. * `q.push()`.
  2930. * Invoked with (task, callback).
  2931. * @param {number} concurrency - An `integer` for determining how many `worker`
  2932. * functions should be run in parallel. If omitted, the concurrency defaults to
  2933. * `1`. If the concurrency is `0`, an error is thrown.
  2934. * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two
  2935. * differences between `queue` and `priorityQueue` objects:
  2936. * * `push(task, priority, [callback])` - `priority` should be a number. If an
  2937. * array of `tasks` is given, all tasks will be assigned the same priority.
  2938. * * The `unshift` method was removed.
  2939. */
  2940. function priorityQueue(worker, concurrency) {
  2941. // Start with a normal queue
  2942. var q = queue$1(worker, concurrency);
  2943. // Override push to accept second parameter representing priority
  2944. q.push = function(data, priority = 0, callback = () => {}) {
  2945. if (typeof callback !== 'function') {
  2946. throw new Error('task callback must be a function');
  2947. }
  2948. q.started = true;
  2949. if (!Array.isArray(data)) {
  2950. data = [data];
  2951. }
  2952. if (data.length === 0) {
  2953. // call drain immediately if there are no tasks
  2954. return setImmediate$1(() => q.drain());
  2955. }
  2956. var nextNode = q._tasks.head;
  2957. while (nextNode && priority >= nextNode.priority) {
  2958. nextNode = nextNode.next;
  2959. }
  2960. for (var i = 0, l = data.length; i < l; i++) {
  2961. var item = {
  2962. data: data[i],
  2963. priority,
  2964. callback
  2965. };
  2966. if (nextNode) {
  2967. q._tasks.insertBefore(nextNode, item);
  2968. } else {
  2969. q._tasks.push(item);
  2970. }
  2971. }
  2972. setImmediate$1(q.process);
  2973. };
  2974. // Remove unshift function
  2975. delete q.unshift;
  2976. return q;
  2977. }
  2978. /**
  2979. * Runs the `tasks` array of functions in parallel, without waiting until the
  2980. * previous function has completed. Once any of the `tasks` complete or pass an
  2981. * error to its callback, the main `callback` is immediately called. It's
  2982. * equivalent to `Promise.race()`.
  2983. *
  2984. * @name race
  2985. * @static
  2986. * @memberOf module:ControlFlow
  2987. * @method
  2988. * @category Control Flow
  2989. * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
  2990. * to run. Each function can complete with an optional `result` value.
  2991. * @param {Function} callback - A callback to run once any of the functions have
  2992. * completed. This function gets an error or result from the first function that
  2993. * completed. Invoked with (err, result).
  2994. * @returns undefined
  2995. * @example
  2996. *
  2997. * async.race([
  2998. * function(callback) {
  2999. * setTimeout(function() {
  3000. * callback(null, 'one');
  3001. * }, 200);
  3002. * },
  3003. * function(callback) {
  3004. * setTimeout(function() {
  3005. * callback(null, 'two');
  3006. * }, 100);
  3007. * }
  3008. * ],
  3009. * // main callback
  3010. * function(err, result) {
  3011. * // the result will be equal to 'two' as it finishes earlier
  3012. * });
  3013. */
  3014. function race(tasks, callback) {
  3015. callback = once(callback);
  3016. if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
  3017. if (!tasks.length) return callback();
  3018. for (var i = 0, l = tasks.length; i < l; i++) {
  3019. wrapAsync(tasks[i])(callback);
  3020. }
  3021. }
  3022. var race$1 = awaitify(race, 2);
  3023. /**
  3024. * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
  3025. *
  3026. * @name reduceRight
  3027. * @static
  3028. * @memberOf module:Collections
  3029. * @method
  3030. * @see [async.reduce]{@link module:Collections.reduce}
  3031. * @alias foldr
  3032. * @category Collection
  3033. * @param {Array} array - A collection to iterate over.
  3034. * @param {*} memo - The initial state of the reduction.
  3035. * @param {AsyncFunction} iteratee - A function applied to each item in the
  3036. * array to produce the next step in the reduction.
  3037. * The `iteratee` should complete with the next state of the reduction.
  3038. * If the iteratee complete with an error, the reduction is stopped and the
  3039. * main `callback` is immediately called with the error.
  3040. * Invoked with (memo, item, callback).
  3041. * @param {Function} [callback] - A callback which is called after all the
  3042. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  3043. * (err, result).
  3044. * @returns {Promise} a promise, if no callback is passed
  3045. */
  3046. function reduceRight (array, memo, iteratee, callback) {
  3047. var reversed = [...array].reverse();
  3048. return reduce$1(reversed, memo, iteratee, callback);
  3049. }
  3050. /**
  3051. * Wraps the async function in another function that always completes with a
  3052. * result object, even when it errors.
  3053. *
  3054. * The result object has either the property `error` or `value`.
  3055. *
  3056. * @name reflect
  3057. * @static
  3058. * @memberOf module:Utils
  3059. * @method
  3060. * @category Util
  3061. * @param {AsyncFunction} fn - The async function you want to wrap
  3062. * @returns {Function} - A function that always passes null to it's callback as
  3063. * the error. The second argument to the callback will be an `object` with
  3064. * either an `error` or a `value` property.
  3065. * @example
  3066. *
  3067. * async.parallel([
  3068. * async.reflect(function(callback) {
  3069. * // do some stuff ...
  3070. * callback(null, 'one');
  3071. * }),
  3072. * async.reflect(function(callback) {
  3073. * // do some more stuff but error ...
  3074. * callback('bad stuff happened');
  3075. * }),
  3076. * async.reflect(function(callback) {
  3077. * // do some more stuff ...
  3078. * callback(null, 'two');
  3079. * })
  3080. * ],
  3081. * // optional callback
  3082. * function(err, results) {
  3083. * // values
  3084. * // results[0].value = 'one'
  3085. * // results[1].error = 'bad stuff happened'
  3086. * // results[2].value = 'two'
  3087. * });
  3088. */
  3089. function reflect(fn) {
  3090. var _fn = wrapAsync(fn);
  3091. return initialParams(function reflectOn(args, reflectCallback) {
  3092. args.push((error, ...cbArgs) => {
  3093. if (error) {
  3094. return reflectCallback(null, { error });
  3095. }
  3096. var value = cbArgs;
  3097. if (cbArgs.length <= 1) {
  3098. [value] = cbArgs;
  3099. }
  3100. reflectCallback(null, { value });
  3101. });
  3102. return _fn.apply(this, args);
  3103. });
  3104. }
  3105. /**
  3106. * A helper function that wraps an array or an object of functions with `reflect`.
  3107. *
  3108. * @name reflectAll
  3109. * @static
  3110. * @memberOf module:Utils
  3111. * @method
  3112. * @see [async.reflect]{@link module:Utils.reflect}
  3113. * @category Util
  3114. * @param {Array|Object|Iterable} tasks - The collection of
  3115. * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.
  3116. * @returns {Array} Returns an array of async functions, each wrapped in
  3117. * `async.reflect`
  3118. * @example
  3119. *
  3120. * let tasks = [
  3121. * function(callback) {
  3122. * setTimeout(function() {
  3123. * callback(null, 'one');
  3124. * }, 200);
  3125. * },
  3126. * function(callback) {
  3127. * // do some more stuff but error ...
  3128. * callback(new Error('bad stuff happened'));
  3129. * },
  3130. * function(callback) {
  3131. * setTimeout(function() {
  3132. * callback(null, 'two');
  3133. * }, 100);
  3134. * }
  3135. * ];
  3136. *
  3137. * async.parallel(async.reflectAll(tasks),
  3138. * // optional callback
  3139. * function(err, results) {
  3140. * // values
  3141. * // results[0].value = 'one'
  3142. * // results[1].error = Error('bad stuff happened')
  3143. * // results[2].value = 'two'
  3144. * });
  3145. *
  3146. * // an example using an object instead of an array
  3147. * let tasks = {
  3148. * one: function(callback) {
  3149. * setTimeout(function() {
  3150. * callback(null, 'one');
  3151. * }, 200);
  3152. * },
  3153. * two: function(callback) {
  3154. * callback('two');
  3155. * },
  3156. * three: function(callback) {
  3157. * setTimeout(function() {
  3158. * callback(null, 'three');
  3159. * }, 100);
  3160. * }
  3161. * };
  3162. *
  3163. * async.parallel(async.reflectAll(tasks),
  3164. * // optional callback
  3165. * function(err, results) {
  3166. * // values
  3167. * // results.one.value = 'one'
  3168. * // results.two.error = 'two'
  3169. * // results.three.value = 'three'
  3170. * });
  3171. */
  3172. function reflectAll(tasks) {
  3173. var results;
  3174. if (Array.isArray(tasks)) {
  3175. results = tasks.map(reflect);
  3176. } else {
  3177. results = {};
  3178. Object.keys(tasks).forEach(key => {
  3179. results[key] = reflect.call(this, tasks[key]);
  3180. });
  3181. }
  3182. return results;
  3183. }
  3184. function reject(eachfn, arr, _iteratee, callback) {
  3185. const iteratee = wrapAsync(_iteratee);
  3186. return _filter(eachfn, arr, (value, cb) => {
  3187. iteratee(value, (err, v) => {
  3188. cb(err, !v);
  3189. });
  3190. }, callback);
  3191. }
  3192. /**
  3193. * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
  3194. *
  3195. * @name reject
  3196. * @static
  3197. * @memberOf module:Collections
  3198. * @method
  3199. * @see [async.filter]{@link module:Collections.filter}
  3200. * @category Collection
  3201. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  3202. * @param {Function} iteratee - An async truth test to apply to each item in
  3203. * `coll`.
  3204. * The should complete with a boolean value as its `result`.
  3205. * Invoked with (item, callback).
  3206. * @param {Function} [callback] - A callback which is called after all the
  3207. * `iteratee` functions have finished. Invoked with (err, results).
  3208. * @returns {Promise} a promise, if no callback is passed
  3209. * @example
  3210. *
  3211. * async.reject(['file1','file2','file3'], function(filePath, callback) {
  3212. * fs.access(filePath, function(err) {
  3213. * callback(null, !err)
  3214. * });
  3215. * }, function(err, results) {
  3216. * // results now equals an array of missing files
  3217. * createFiles(results);
  3218. * });
  3219. */
  3220. function reject$1 (coll, iteratee, callback) {
  3221. return reject(eachOf$1, coll, iteratee, callback)
  3222. }
  3223. var reject$2 = awaitify(reject$1, 3);
  3224. /**
  3225. * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
  3226. * time.
  3227. *
  3228. * @name rejectLimit
  3229. * @static
  3230. * @memberOf module:Collections
  3231. * @method
  3232. * @see [async.reject]{@link module:Collections.reject}
  3233. * @category Collection
  3234. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  3235. * @param {number} limit - The maximum number of async operations at a time.
  3236. * @param {Function} iteratee - An async truth test to apply to each item in
  3237. * `coll`.
  3238. * The should complete with a boolean value as its `result`.
  3239. * Invoked with (item, callback).
  3240. * @param {Function} [callback] - A callback which is called after all the
  3241. * `iteratee` functions have finished. Invoked with (err, results).
  3242. * @returns {Promise} a promise, if no callback is passed
  3243. */
  3244. function rejectLimit (coll, limit, iteratee, callback) {
  3245. return reject(eachOfLimit(limit), coll, iteratee, callback)
  3246. }
  3247. var rejectLimit$1 = awaitify(rejectLimit, 4);
  3248. /**
  3249. * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
  3250. *
  3251. * @name rejectSeries
  3252. * @static
  3253. * @memberOf module:Collections
  3254. * @method
  3255. * @see [async.reject]{@link module:Collections.reject}
  3256. * @category Collection
  3257. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  3258. * @param {Function} iteratee - An async truth test to apply to each item in
  3259. * `coll`.
  3260. * The should complete with a boolean value as its `result`.
  3261. * Invoked with (item, callback).
  3262. * @param {Function} [callback] - A callback which is called after all the
  3263. * `iteratee` functions have finished. Invoked with (err, results).
  3264. * @returns {Promise} a promise, if no callback is passed
  3265. */
  3266. function rejectSeries (coll, iteratee, callback) {
  3267. return reject(eachOfSeries$1, coll, iteratee, callback)
  3268. }
  3269. var rejectSeries$1 = awaitify(rejectSeries, 3);
  3270. function constant$1(value) {
  3271. return function () {
  3272. return value;
  3273. }
  3274. }
  3275. /**
  3276. * Attempts to get a successful response from `task` no more than `times` times
  3277. * before returning an error. If the task is successful, the `callback` will be
  3278. * passed the result of the successful task. If all attempts fail, the callback
  3279. * will be passed the error and result (if any) of the final attempt.
  3280. *
  3281. * @name retry
  3282. * @static
  3283. * @memberOf module:ControlFlow
  3284. * @method
  3285. * @category Control Flow
  3286. * @see [async.retryable]{@link module:ControlFlow.retryable}
  3287. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
  3288. * object with `times` and `interval` or a number.
  3289. * * `times` - The number of attempts to make before giving up. The default
  3290. * is `5`.
  3291. * * `interval` - The time to wait between retries, in milliseconds. The
  3292. * default is `0`. The interval may also be specified as a function of the
  3293. * retry count (see example).
  3294. * * `errorFilter` - An optional synchronous function that is invoked on
  3295. * erroneous result. If it returns `true` the retry attempts will continue;
  3296. * if the function returns `false` the retry flow is aborted with the current
  3297. * attempt's error and result being returned to the final callback.
  3298. * Invoked with (err).
  3299. * * If `opts` is a number, the number specifies the number of times to retry,
  3300. * with the default interval of `0`.
  3301. * @param {AsyncFunction} task - An async function to retry.
  3302. * Invoked with (callback).
  3303. * @param {Function} [callback] - An optional callback which is called when the
  3304. * task has succeeded, or after the final failed attempt. It receives the `err`
  3305. * and `result` arguments of the last attempt at completing the `task`. Invoked
  3306. * with (err, results).
  3307. * @returns {Promise} a promise if no callback provided
  3308. *
  3309. * @example
  3310. *
  3311. * // The `retry` function can be used as a stand-alone control flow by passing
  3312. * // a callback, as shown below:
  3313. *
  3314. * // try calling apiMethod 3 times
  3315. * async.retry(3, apiMethod, function(err, result) {
  3316. * // do something with the result
  3317. * });
  3318. *
  3319. * // try calling apiMethod 3 times, waiting 200 ms between each retry
  3320. * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
  3321. * // do something with the result
  3322. * });
  3323. *
  3324. * // try calling apiMethod 10 times with exponential backoff
  3325. * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
  3326. * async.retry({
  3327. * times: 10,
  3328. * interval: function(retryCount) {
  3329. * return 50 * Math.pow(2, retryCount);
  3330. * }
  3331. * }, apiMethod, function(err, result) {
  3332. * // do something with the result
  3333. * });
  3334. *
  3335. * // try calling apiMethod the default 5 times no delay between each retry
  3336. * async.retry(apiMethod, function(err, result) {
  3337. * // do something with the result
  3338. * });
  3339. *
  3340. * // try calling apiMethod only when error condition satisfies, all other
  3341. * // errors will abort the retry control flow and return to final callback
  3342. * async.retry({
  3343. * errorFilter: function(err) {
  3344. * return err.message === 'Temporary error'; // only retry on a specific error
  3345. * }
  3346. * }, apiMethod, function(err, result) {
  3347. * // do something with the result
  3348. * });
  3349. *
  3350. * // to retry individual methods that are not as reliable within other
  3351. * // control flow functions, use the `retryable` wrapper:
  3352. * async.auto({
  3353. * users: api.getUsers.bind(api),
  3354. * payments: async.retryable(3, api.getPayments.bind(api))
  3355. * }, function(err, results) {
  3356. * // do something with the results
  3357. * });
  3358. *
  3359. */
  3360. const DEFAULT_TIMES = 5;
  3361. const DEFAULT_INTERVAL = 0;
  3362. function retry(opts, task, callback) {
  3363. var options = {
  3364. times: DEFAULT_TIMES,
  3365. intervalFunc: constant$1(DEFAULT_INTERVAL)
  3366. };
  3367. if (arguments.length < 3 && typeof opts === 'function') {
  3368. callback = task || promiseCallback();
  3369. task = opts;
  3370. } else {
  3371. parseTimes(options, opts);
  3372. callback = callback || promiseCallback();
  3373. }
  3374. if (typeof task !== 'function') {
  3375. throw new Error("Invalid arguments for async.retry");
  3376. }
  3377. var _task = wrapAsync(task);
  3378. var attempt = 1;
  3379. function retryAttempt() {
  3380. _task((err, ...args) => {
  3381. if (err === false) return
  3382. if (err && attempt++ < options.times &&
  3383. (typeof options.errorFilter != 'function' ||
  3384. options.errorFilter(err))) {
  3385. setTimeout(retryAttempt, options.intervalFunc(attempt));
  3386. } else {
  3387. callback(err, ...args);
  3388. }
  3389. });
  3390. }
  3391. retryAttempt();
  3392. return callback[PROMISE_SYMBOL]
  3393. }
  3394. function parseTimes(acc, t) {
  3395. if (typeof t === 'object') {
  3396. acc.times = +t.times || DEFAULT_TIMES;
  3397. acc.intervalFunc = typeof t.interval === 'function' ?
  3398. t.interval :
  3399. constant$1(+t.interval || DEFAULT_INTERVAL);
  3400. acc.errorFilter = t.errorFilter;
  3401. } else if (typeof t === 'number' || typeof t === 'string') {
  3402. acc.times = +t || DEFAULT_TIMES;
  3403. } else {
  3404. throw new Error("Invalid arguments for async.retry");
  3405. }
  3406. }
  3407. /**
  3408. * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method
  3409. * wraps a task and makes it retryable, rather than immediately calling it
  3410. * with retries.
  3411. *
  3412. * @name retryable
  3413. * @static
  3414. * @memberOf module:ControlFlow
  3415. * @method
  3416. * @see [async.retry]{@link module:ControlFlow.retry}
  3417. * @category Control Flow
  3418. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
  3419. * options, exactly the same as from `retry`, except for a `opts.arity` that
  3420. * is the arity of the `task` function, defaulting to `task.length`
  3421. * @param {AsyncFunction} task - the asynchronous function to wrap.
  3422. * This function will be passed any arguments passed to the returned wrapper.
  3423. * Invoked with (...args, callback).
  3424. * @returns {AsyncFunction} The wrapped function, which when invoked, will
  3425. * retry on an error, based on the parameters specified in `opts`.
  3426. * This function will accept the same parameters as `task`.
  3427. * @example
  3428. *
  3429. * async.auto({
  3430. * dep1: async.retryable(3, getFromFlakyService),
  3431. * process: ["dep1", async.retryable(3, function (results, cb) {
  3432. * maybeProcessData(results.dep1, cb);
  3433. * })]
  3434. * }, callback);
  3435. */
  3436. function retryable (opts, task) {
  3437. if (!task) {
  3438. task = opts;
  3439. opts = null;
  3440. }
  3441. let arity = (opts && opts.arity) || task.length;
  3442. if (isAsync(task)) {
  3443. arity += 1;
  3444. }
  3445. var _task = wrapAsync(task);
  3446. return initialParams((args, callback) => {
  3447. if (args.length < arity - 1 || callback == null) {
  3448. args.push(callback);
  3449. callback = promiseCallback();
  3450. }
  3451. function taskFn(cb) {
  3452. _task(...args, cb);
  3453. }
  3454. if (opts) retry(opts, taskFn, callback);
  3455. else retry(taskFn, callback);
  3456. return callback[PROMISE_SYMBOL]
  3457. });
  3458. }
  3459. /**
  3460. * Run the functions in the `tasks` collection in series, each one running once
  3461. * the previous function has completed. If any functions in the series pass an
  3462. * error to its callback, no more functions are run, and `callback` is
  3463. * immediately called with the value of the error. Otherwise, `callback`
  3464. * receives an array of results when `tasks` have completed.
  3465. *
  3466. * It is also possible to use an object instead of an array. Each property will
  3467. * be run as a function, and the results will be passed to the final `callback`
  3468. * as an object instead of an array. This can be a more readable way of handling
  3469. * results from {@link async.series}.
  3470. *
  3471. * **Note** that while many implementations preserve the order of object
  3472. * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
  3473. * explicitly states that
  3474. *
  3475. * > The mechanics and order of enumerating the properties is not specified.
  3476. *
  3477. * So if you rely on the order in which your series of functions are executed,
  3478. * and want this to work on all platforms, consider using an array.
  3479. *
  3480. * @name series
  3481. * @static
  3482. * @memberOf module:ControlFlow
  3483. * @method
  3484. * @category Control Flow
  3485. * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing
  3486. * [async functions]{@link AsyncFunction} to run in series.
  3487. * Each function can complete with any number of optional `result` values.
  3488. * @param {Function} [callback] - An optional callback to run once all the
  3489. * functions have completed. This function gets a results array (or object)
  3490. * containing all the result arguments passed to the `task` callbacks. Invoked
  3491. * with (err, result).
  3492. * @return {Promise} a promise, if no callback is passed
  3493. * @example
  3494. * async.series([
  3495. * function(callback) {
  3496. * // do some stuff ...
  3497. * callback(null, 'one');
  3498. * },
  3499. * function(callback) {
  3500. * // do some more stuff ...
  3501. * callback(null, 'two');
  3502. * }
  3503. * ],
  3504. * // optional callback
  3505. * function(err, results) {
  3506. * // results is now equal to ['one', 'two']
  3507. * });
  3508. *
  3509. * async.series({
  3510. * one: function(callback) {
  3511. * setTimeout(function() {
  3512. * callback(null, 1);
  3513. * }, 200);
  3514. * },
  3515. * two: function(callback){
  3516. * setTimeout(function() {
  3517. * callback(null, 2);
  3518. * }, 100);
  3519. * }
  3520. * }, function(err, results) {
  3521. * // results is now equal to: {one: 1, two: 2}
  3522. * });
  3523. */
  3524. function series(tasks, callback) {
  3525. return _parallel(eachOfSeries$1, tasks, callback);
  3526. }
  3527. /**
  3528. * Returns `true` if at least one element in the `coll` satisfies an async test.
  3529. * If any iteratee call returns `true`, the main `callback` is immediately
  3530. * called.
  3531. *
  3532. * @name some
  3533. * @static
  3534. * @memberOf module:Collections
  3535. * @method
  3536. * @alias any
  3537. * @category Collection
  3538. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  3539. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  3540. * in the collections in parallel.
  3541. * The iteratee should complete with a boolean `result` value.
  3542. * Invoked with (item, callback).
  3543. * @param {Function} [callback] - A callback which is called as soon as any
  3544. * iteratee returns `true`, or after all the iteratee functions have finished.
  3545. * Result will be either `true` or `false` depending on the values of the async
  3546. * tests. Invoked with (err, result).
  3547. * @returns {Promise} a promise, if no callback provided
  3548. * @example
  3549. *
  3550. * async.some(['file1','file2','file3'], function(filePath, callback) {
  3551. * fs.access(filePath, function(err) {
  3552. * callback(null, !err)
  3553. * });
  3554. * }, function(err, result) {
  3555. * // if result is true then at least one of the files exists
  3556. * });
  3557. */
  3558. function some(coll, iteratee, callback) {
  3559. return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback)
  3560. }
  3561. var some$1 = awaitify(some, 3);
  3562. /**
  3563. * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
  3564. *
  3565. * @name someLimit
  3566. * @static
  3567. * @memberOf module:Collections
  3568. * @method
  3569. * @see [async.some]{@link module:Collections.some}
  3570. * @alias anyLimit
  3571. * @category Collection
  3572. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  3573. * @param {number} limit - The maximum number of async operations at a time.
  3574. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  3575. * in the collections in parallel.
  3576. * The iteratee should complete with a boolean `result` value.
  3577. * Invoked with (item, callback).
  3578. * @param {Function} [callback] - A callback which is called as soon as any
  3579. * iteratee returns `true`, or after all the iteratee functions have finished.
  3580. * Result will be either `true` or `false` depending on the values of the async
  3581. * tests. Invoked with (err, result).
  3582. * @returns {Promise} a promise, if no callback provided
  3583. */
  3584. function someLimit(coll, limit, iteratee, callback) {
  3585. return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback)
  3586. }
  3587. var someLimit$1 = awaitify(someLimit, 4);
  3588. /**
  3589. * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
  3590. *
  3591. * @name someSeries
  3592. * @static
  3593. * @memberOf module:Collections
  3594. * @method
  3595. * @see [async.some]{@link module:Collections.some}
  3596. * @alias anySeries
  3597. * @category Collection
  3598. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  3599. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  3600. * in the collections in series.
  3601. * The iteratee should complete with a boolean `result` value.
  3602. * Invoked with (item, callback).
  3603. * @param {Function} [callback] - A callback which is called as soon as any
  3604. * iteratee returns `true`, or after all the iteratee functions have finished.
  3605. * Result will be either `true` or `false` depending on the values of the async
  3606. * tests. Invoked with (err, result).
  3607. * @returns {Promise} a promise, if no callback provided
  3608. */
  3609. function someSeries(coll, iteratee, callback) {
  3610. return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback)
  3611. }
  3612. var someSeries$1 = awaitify(someSeries, 3);
  3613. /**
  3614. * Sorts a list by the results of running each `coll` value through an async
  3615. * `iteratee`.
  3616. *
  3617. * @name sortBy
  3618. * @static
  3619. * @memberOf module:Collections
  3620. * @method
  3621. * @category Collection
  3622. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  3623. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  3624. * `coll`.
  3625. * The iteratee should complete with a value to use as the sort criteria as
  3626. * its `result`.
  3627. * Invoked with (item, callback).
  3628. * @param {Function} callback - A callback which is called after all the
  3629. * `iteratee` functions have finished, or an error occurs. Results is the items
  3630. * from the original `coll` sorted by the values returned by the `iteratee`
  3631. * calls. Invoked with (err, results).
  3632. * @returns {Promise} a promise, if no callback passed
  3633. * @example
  3634. *
  3635. * async.sortBy(['file1','file2','file3'], function(file, callback) {
  3636. * fs.stat(file, function(err, stats) {
  3637. * callback(err, stats.mtime);
  3638. * });
  3639. * }, function(err, results) {
  3640. * // results is now the original array of files sorted by
  3641. * // modified date
  3642. * });
  3643. *
  3644. * // By modifying the callback parameter the
  3645. * // sorting order can be influenced:
  3646. *
  3647. * // ascending order
  3648. * async.sortBy([1,9,3,5], function(x, callback) {
  3649. * callback(null, x);
  3650. * }, function(err,result) {
  3651. * // result callback
  3652. * });
  3653. *
  3654. * // descending order
  3655. * async.sortBy([1,9,3,5], function(x, callback) {
  3656. * callback(null, x*-1); //<- x*-1 instead of x, turns the order around
  3657. * }, function(err,result) {
  3658. * // result callback
  3659. * });
  3660. */
  3661. function sortBy (coll, iteratee, callback) {
  3662. var _iteratee = wrapAsync(iteratee);
  3663. return map$1(coll, (x, iterCb) => {
  3664. _iteratee(x, (err, criteria) => {
  3665. if (err) return iterCb(err);
  3666. iterCb(null, {value: x, criteria});
  3667. });
  3668. }, (err, results) => {
  3669. if (err) return callback(err);
  3670. callback(null, results.sort(comparator).map(v => v.value));
  3671. });
  3672. function comparator(left, right) {
  3673. var a = left.criteria, b = right.criteria;
  3674. return a < b ? -1 : a > b ? 1 : 0;
  3675. }
  3676. }
  3677. var sortBy$1 = awaitify(sortBy, 3);
  3678. /**
  3679. * Sets a time limit on an asynchronous function. If the function does not call
  3680. * its callback within the specified milliseconds, it will be called with a
  3681. * timeout error. The code property for the error object will be `'ETIMEDOUT'`.
  3682. *
  3683. * @name timeout
  3684. * @static
  3685. * @memberOf module:Utils
  3686. * @method
  3687. * @category Util
  3688. * @param {AsyncFunction} asyncFn - The async function to limit in time.
  3689. * @param {number} milliseconds - The specified time limit.
  3690. * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
  3691. * to timeout Error for more information..
  3692. * @returns {AsyncFunction} Returns a wrapped function that can be used with any
  3693. * of the control flow functions.
  3694. * Invoke this function with the same parameters as you would `asyncFunc`.
  3695. * @example
  3696. *
  3697. * function myFunction(foo, callback) {
  3698. * doAsyncTask(foo, function(err, data) {
  3699. * // handle errors
  3700. * if (err) return callback(err);
  3701. *
  3702. * // do some stuff ...
  3703. *
  3704. * // return processed data
  3705. * return callback(null, data);
  3706. * });
  3707. * }
  3708. *
  3709. * var wrapped = async.timeout(myFunction, 1000);
  3710. *
  3711. * // call `wrapped` as you would `myFunction`
  3712. * wrapped({ bar: 'bar' }, function(err, data) {
  3713. * // if `myFunction` takes < 1000 ms to execute, `err`
  3714. * // and `data` will have their expected values
  3715. *
  3716. * // else `err` will be an Error with the code 'ETIMEDOUT'
  3717. * });
  3718. */
  3719. function timeout(asyncFn, milliseconds, info) {
  3720. var fn = wrapAsync(asyncFn);
  3721. return initialParams((args, callback) => {
  3722. var timedOut = false;
  3723. var timer;
  3724. function timeoutCallback() {
  3725. var name = asyncFn.name || 'anonymous';
  3726. var error = new Error('Callback function "' + name + '" timed out.');
  3727. error.code = 'ETIMEDOUT';
  3728. if (info) {
  3729. error.info = info;
  3730. }
  3731. timedOut = true;
  3732. callback(error);
  3733. }
  3734. args.push((...cbArgs) => {
  3735. if (!timedOut) {
  3736. callback(...cbArgs);
  3737. clearTimeout(timer);
  3738. }
  3739. });
  3740. // setup timer and call original function
  3741. timer = setTimeout(timeoutCallback, milliseconds);
  3742. fn(...args);
  3743. });
  3744. }
  3745. function range(size) {
  3746. var result = Array(size);
  3747. while (size--) {
  3748. result[size] = size;
  3749. }
  3750. return result;
  3751. }
  3752. /**
  3753. * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a
  3754. * time.
  3755. *
  3756. * @name timesLimit
  3757. * @static
  3758. * @memberOf module:ControlFlow
  3759. * @method
  3760. * @see [async.times]{@link module:ControlFlow.times}
  3761. * @category Control Flow
  3762. * @param {number} count - The number of times to run the function.
  3763. * @param {number} limit - The maximum number of async operations at a time.
  3764. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  3765. * Invoked with the iteration index and a callback: (n, next).
  3766. * @param {Function} callback - see [async.map]{@link module:Collections.map}.
  3767. * @returns {Promise} a promise, if no callback is provided
  3768. */
  3769. function timesLimit(count, limit, iteratee, callback) {
  3770. var _iteratee = wrapAsync(iteratee);
  3771. return mapLimit$1(range(count), limit, _iteratee, callback);
  3772. }
  3773. /**
  3774. * Calls the `iteratee` function `n` times, and accumulates results in the same
  3775. * manner you would use with [map]{@link module:Collections.map}.
  3776. *
  3777. * @name times
  3778. * @static
  3779. * @memberOf module:ControlFlow
  3780. * @method
  3781. * @see [async.map]{@link module:Collections.map}
  3782. * @category Control Flow
  3783. * @param {number} n - The number of times to run the function.
  3784. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  3785. * Invoked with the iteration index and a callback: (n, next).
  3786. * @param {Function} callback - see {@link module:Collections.map}.
  3787. * @returns {Promise} a promise, if no callback is provided
  3788. * @example
  3789. *
  3790. * // Pretend this is some complicated async factory
  3791. * var createUser = function(id, callback) {
  3792. * callback(null, {
  3793. * id: 'user' + id
  3794. * });
  3795. * };
  3796. *
  3797. * // generate 5 users
  3798. * async.times(5, function(n, next) {
  3799. * createUser(n, function(err, user) {
  3800. * next(err, user);
  3801. * });
  3802. * }, function(err, users) {
  3803. * // we should now have 5 users
  3804. * });
  3805. */
  3806. function times (n, iteratee, callback) {
  3807. return timesLimit(n, Infinity, iteratee, callback)
  3808. }
  3809. /**
  3810. * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.
  3811. *
  3812. * @name timesSeries
  3813. * @static
  3814. * @memberOf module:ControlFlow
  3815. * @method
  3816. * @see [async.times]{@link module:ControlFlow.times}
  3817. * @category Control Flow
  3818. * @param {number} n - The number of times to run the function.
  3819. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  3820. * Invoked with the iteration index and a callback: (n, next).
  3821. * @param {Function} callback - see {@link module:Collections.map}.
  3822. * @returns {Promise} a promise, if no callback is provided
  3823. */
  3824. function timesSeries (n, iteratee, callback) {
  3825. return timesLimit(n, 1, iteratee, callback)
  3826. }
  3827. /**
  3828. * A relative of `reduce`. Takes an Object or Array, and iterates over each
  3829. * element in parallel, each step potentially mutating an `accumulator` value.
  3830. * The type of the accumulator defaults to the type of collection passed in.
  3831. *
  3832. * @name transform
  3833. * @static
  3834. * @memberOf module:Collections
  3835. * @method
  3836. * @category Collection
  3837. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  3838. * @param {*} [accumulator] - The initial state of the transform. If omitted,
  3839. * it will default to an empty Object or Array, depending on the type of `coll`
  3840. * @param {AsyncFunction} iteratee - A function applied to each item in the
  3841. * collection that potentially modifies the accumulator.
  3842. * Invoked with (accumulator, item, key, callback).
  3843. * @param {Function} [callback] - A callback which is called after all the
  3844. * `iteratee` functions have finished. Result is the transformed accumulator.
  3845. * Invoked with (err, result).
  3846. * @returns {Promise} a promise, if no callback provided
  3847. * @example
  3848. *
  3849. * async.transform([1,2,3], function(acc, item, index, callback) {
  3850. * // pointless async:
  3851. * process.nextTick(function() {
  3852. * acc[index] = item * 2
  3853. * callback(null)
  3854. * });
  3855. * }, function(err, result) {
  3856. * // result is now equal to [2, 4, 6]
  3857. * });
  3858. *
  3859. * @example
  3860. *
  3861. * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
  3862. * setImmediate(function () {
  3863. * obj[key] = val * 2;
  3864. * callback();
  3865. * })
  3866. * }, function (err, result) {
  3867. * // result is equal to {a: 2, b: 4, c: 6}
  3868. * })
  3869. */
  3870. function transform (coll, accumulator, iteratee, callback) {
  3871. if (arguments.length <= 3 && typeof accumulator === 'function') {
  3872. callback = iteratee;
  3873. iteratee = accumulator;
  3874. accumulator = Array.isArray(coll) ? [] : {};
  3875. }
  3876. callback = once(callback || promiseCallback());
  3877. var _iteratee = wrapAsync(iteratee);
  3878. eachOf$1(coll, (v, k, cb) => {
  3879. _iteratee(accumulator, v, k, cb);
  3880. }, err => callback(err, accumulator));
  3881. return callback[PROMISE_SYMBOL]
  3882. }
  3883. /**
  3884. * It runs each task in series but stops whenever any of the functions were
  3885. * successful. If one of the tasks were successful, the `callback` will be
  3886. * passed the result of the successful task. If all tasks fail, the callback
  3887. * will be passed the error and result (if any) of the final attempt.
  3888. *
  3889. * @name tryEach
  3890. * @static
  3891. * @memberOf module:ControlFlow
  3892. * @method
  3893. * @category Control Flow
  3894. * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to
  3895. * run, each function is passed a `callback(err, result)` it must call on
  3896. * completion with an error `err` (which can be `null`) and an optional `result`
  3897. * value.
  3898. * @param {Function} [callback] - An optional callback which is called when one
  3899. * of the tasks has succeeded, or all have failed. It receives the `err` and
  3900. * `result` arguments of the last attempt at completing the `task`. Invoked with
  3901. * (err, results).
  3902. * @returns {Promise} a promise, if no callback is passed
  3903. * @example
  3904. * async.tryEach([
  3905. * function getDataFromFirstWebsite(callback) {
  3906. * // Try getting the data from the first website
  3907. * callback(err, data);
  3908. * },
  3909. * function getDataFromSecondWebsite(callback) {
  3910. * // First website failed,
  3911. * // Try getting the data from the backup website
  3912. * callback(err, data);
  3913. * }
  3914. * ],
  3915. * // optional callback
  3916. * function(err, results) {
  3917. * Now do something with the data.
  3918. * });
  3919. *
  3920. */
  3921. function tryEach(tasks, callback) {
  3922. var error = null;
  3923. var result;
  3924. return eachSeries$1(tasks, (task, taskCb) => {
  3925. wrapAsync(task)((err, ...args) => {
  3926. if (args.length < 2) {
  3927. [result] = args;
  3928. } else {
  3929. result = args;
  3930. }
  3931. error = err;
  3932. taskCb(err ? null : {});
  3933. });
  3934. }, () => callback(error, result));
  3935. }
  3936. var tryEach$1 = awaitify(tryEach);
  3937. /**
  3938. * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,
  3939. * unmemoized form. Handy for testing.
  3940. *
  3941. * @name unmemoize
  3942. * @static
  3943. * @memberOf module:Utils
  3944. * @method
  3945. * @see [async.memoize]{@link module:Utils.memoize}
  3946. * @category Util
  3947. * @param {AsyncFunction} fn - the memoized function
  3948. * @returns {AsyncFunction} a function that calls the original unmemoized function
  3949. */
  3950. function unmemoize(fn) {
  3951. return (...args) => {
  3952. return (fn.unmemoized || fn)(...args);
  3953. };
  3954. }
  3955. /**
  3956. * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
  3957. * stopped, or an error occurs.
  3958. *
  3959. * @name whilst
  3960. * @static
  3961. * @memberOf module:ControlFlow
  3962. * @method
  3963. * @category Control Flow
  3964. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  3965. * execution of `iteratee`. Invoked with ().
  3966. * @param {AsyncFunction} iteratee - An async function which is called each time
  3967. * `test` passes. Invoked with (callback).
  3968. * @param {Function} [callback] - A callback which is called after the test
  3969. * function has failed and repeated execution of `iteratee` has stopped. `callback`
  3970. * will be passed an error and any arguments passed to the final `iteratee`'s
  3971. * callback. Invoked with (err, [results]);
  3972. * @returns {Promise} a promise, if no callback is passed
  3973. * @example
  3974. *
  3975. * var count = 0;
  3976. * async.whilst(
  3977. * function test(cb) { cb(null, count < 5;) },
  3978. * function iter(callback) {
  3979. * count++;
  3980. * setTimeout(function() {
  3981. * callback(null, count);
  3982. * }, 1000);
  3983. * },
  3984. * function (err, n) {
  3985. * // 5 seconds have passed, n = 5
  3986. * }
  3987. * );
  3988. */
  3989. function whilst(test, iteratee, callback) {
  3990. callback = onlyOnce(callback);
  3991. var _fn = wrapAsync(iteratee);
  3992. var _test = wrapAsync(test);
  3993. var results;
  3994. function next(err, ...rest) {
  3995. if (err) return callback(err);
  3996. results = rest;
  3997. if (err === false) return;
  3998. _test(check);
  3999. }
  4000. function check(err, truth) {
  4001. if (err) return callback(err);
  4002. if (err === false) return;
  4003. if (!truth) return callback(null, ...results);
  4004. _fn(next);
  4005. }
  4006. return _test(check);
  4007. }
  4008. var whilst$1 = awaitify(whilst, 3);
  4009. /**
  4010. * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when
  4011. * stopped, or an error occurs. `callback` will be passed an error and any
  4012. * arguments passed to the final `iteratee`'s callback.
  4013. *
  4014. * The inverse of [whilst]{@link module:ControlFlow.whilst}.
  4015. *
  4016. * @name until
  4017. * @static
  4018. * @memberOf module:ControlFlow
  4019. * @method
  4020. * @see [async.whilst]{@link module:ControlFlow.whilst}
  4021. * @category Control Flow
  4022. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  4023. * execution of `iteratee`. Invoked with (callback).
  4024. * @param {AsyncFunction} iteratee - An async function which is called each time
  4025. * `test` fails. Invoked with (callback).
  4026. * @param {Function} [callback] - A callback which is called after the test
  4027. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  4028. * will be passed an error and any arguments passed to the final `iteratee`'s
  4029. * callback. Invoked with (err, [results]);
  4030. * @returns {Promise} a promise, if a callback is not passed
  4031. *
  4032. * @example
  4033. * const results = []
  4034. * async.until(function iter(next) {
  4035. * fetchPage(url, (err, body) => {
  4036. * if (err) return next(err)
  4037. * results = results.concat(body.objects)
  4038. * next(err, body)
  4039. * })
  4040. * }, function test(page, cb) {
  4041. * cb(null, page.next == null)
  4042. * }, function done (err) {
  4043. * // all pages have been fetched
  4044. * })
  4045. */
  4046. function until(test, iteratee, callback) {
  4047. const _test = wrapAsync(test);
  4048. return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback);
  4049. }
  4050. /**
  4051. * Runs the `tasks` array of functions in series, each passing their results to
  4052. * the next in the array. However, if any of the `tasks` pass an error to their
  4053. * own callback, the next function is not executed, and the main `callback` is
  4054. * immediately called with the error.
  4055. *
  4056. * @name waterfall
  4057. * @static
  4058. * @memberOf module:ControlFlow
  4059. * @method
  4060. * @category Control Flow
  4061. * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
  4062. * to run.
  4063. * Each function should complete with any number of `result` values.
  4064. * The `result` values will be passed as arguments, in order, to the next task.
  4065. * @param {Function} [callback] - An optional callback to run once all the
  4066. * functions have completed. This will be passed the results of the last task's
  4067. * callback. Invoked with (err, [results]).
  4068. * @returns undefined
  4069. * @example
  4070. *
  4071. * async.waterfall([
  4072. * function(callback) {
  4073. * callback(null, 'one', 'two');
  4074. * },
  4075. * function(arg1, arg2, callback) {
  4076. * // arg1 now equals 'one' and arg2 now equals 'two'
  4077. * callback(null, 'three');
  4078. * },
  4079. * function(arg1, callback) {
  4080. * // arg1 now equals 'three'
  4081. * callback(null, 'done');
  4082. * }
  4083. * ], function (err, result) {
  4084. * // result now equals 'done'
  4085. * });
  4086. *
  4087. * // Or, with named functions:
  4088. * async.waterfall([
  4089. * myFirstFunction,
  4090. * mySecondFunction,
  4091. * myLastFunction,
  4092. * ], function (err, result) {
  4093. * // result now equals 'done'
  4094. * });
  4095. * function myFirstFunction(callback) {
  4096. * callback(null, 'one', 'two');
  4097. * }
  4098. * function mySecondFunction(arg1, arg2, callback) {
  4099. * // arg1 now equals 'one' and arg2 now equals 'two'
  4100. * callback(null, 'three');
  4101. * }
  4102. * function myLastFunction(arg1, callback) {
  4103. * // arg1 now equals 'three'
  4104. * callback(null, 'done');
  4105. * }
  4106. */
  4107. function waterfall (tasks, callback) {
  4108. callback = once(callback);
  4109. if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
  4110. if (!tasks.length) return callback();
  4111. var taskIndex = 0;
  4112. function nextTask(args) {
  4113. var task = wrapAsync(tasks[taskIndex++]);
  4114. task(...args, onlyOnce(next));
  4115. }
  4116. function next(err, ...args) {
  4117. if (err === false) return
  4118. if (err || taskIndex === tasks.length) {
  4119. return callback(err, ...args);
  4120. }
  4121. nextTask(args);
  4122. }
  4123. nextTask([]);
  4124. }
  4125. var waterfall$1 = awaitify(waterfall);
  4126. /**
  4127. * An "async function" in the context of Async is an asynchronous function with
  4128. * a variable number of parameters, with the final parameter being a callback.
  4129. * (`function (arg1, arg2, ..., callback) {}`)
  4130. * The final callback is of the form `callback(err, results...)`, which must be
  4131. * called once the function is completed. The callback should be called with a
  4132. * Error as its first argument to signal that an error occurred.
  4133. * Otherwise, if no error occurred, it should be called with `null` as the first
  4134. * argument, and any additional `result` arguments that may apply, to signal
  4135. * successful completion.
  4136. * The callback must be called exactly once, ideally on a later tick of the
  4137. * JavaScript event loop.
  4138. *
  4139. * This type of function is also referred to as a "Node-style async function",
  4140. * or a "continuation passing-style function" (CPS). Most of the methods of this
  4141. * library are themselves CPS/Node-style async functions, or functions that
  4142. * return CPS/Node-style async functions.
  4143. *
  4144. * Wherever we accept a Node-style async function, we also directly accept an
  4145. * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.
  4146. * In this case, the `async` function will not be passed a final callback
  4147. * argument, and any thrown error will be used as the `err` argument of the
  4148. * implicit callback, and the return value will be used as the `result` value.
  4149. * (i.e. a `rejected` of the returned Promise becomes the `err` callback
  4150. * argument, and a `resolved` value becomes the `result`.)
  4151. *
  4152. * Note, due to JavaScript limitations, we can only detect native `async`
  4153. * functions and not transpilied implementations.
  4154. * Your environment must have `async`/`await` support for this to work.
  4155. * (e.g. Node > v7.6, or a recent version of a modern browser).
  4156. * If you are using `async` functions through a transpiler (e.g. Babel), you
  4157. * must still wrap the function with [asyncify]{@link module:Utils.asyncify},
  4158. * because the `async function` will be compiled to an ordinary function that
  4159. * returns a promise.
  4160. *
  4161. * @typedef {Function} AsyncFunction
  4162. * @static
  4163. */
  4164. var index = {
  4165. apply,
  4166. applyEach: applyEach$1,
  4167. applyEachSeries,
  4168. asyncify,
  4169. auto,
  4170. autoInject,
  4171. cargo,
  4172. cargoQueue: cargo$1,
  4173. compose,
  4174. concat: concat$1,
  4175. concatLimit: concatLimit$1,
  4176. concatSeries: concatSeries$1,
  4177. constant,
  4178. detect: detect$1,
  4179. detectLimit: detectLimit$1,
  4180. detectSeries: detectSeries$1,
  4181. dir,
  4182. doUntil,
  4183. doWhilst: doWhilst$1,
  4184. each,
  4185. eachLimit: eachLimit$2,
  4186. eachOf: eachOf$1,
  4187. eachOfLimit: eachOfLimit$2,
  4188. eachOfSeries: eachOfSeries$1,
  4189. eachSeries: eachSeries$1,
  4190. ensureAsync,
  4191. every: every$1,
  4192. everyLimit: everyLimit$1,
  4193. everySeries: everySeries$1,
  4194. filter: filter$1,
  4195. filterLimit: filterLimit$1,
  4196. filterSeries: filterSeries$1,
  4197. forever: forever$1,
  4198. groupBy,
  4199. groupByLimit: groupByLimit$1,
  4200. groupBySeries,
  4201. log,
  4202. map: map$1,
  4203. mapLimit: mapLimit$1,
  4204. mapSeries: mapSeries$1,
  4205. mapValues,
  4206. mapValuesLimit: mapValuesLimit$1,
  4207. mapValuesSeries,
  4208. memoize,
  4209. nextTick,
  4210. parallel,
  4211. parallelLimit,
  4212. priorityQueue,
  4213. queue: queue$1,
  4214. race: race$1,
  4215. reduce: reduce$1,
  4216. reduceRight,
  4217. reflect,
  4218. reflectAll,
  4219. reject: reject$2,
  4220. rejectLimit: rejectLimit$1,
  4221. rejectSeries: rejectSeries$1,
  4222. retry,
  4223. retryable,
  4224. seq,
  4225. series,
  4226. setImmediate: setImmediate$1,
  4227. some: some$1,
  4228. someLimit: someLimit$1,
  4229. someSeries: someSeries$1,
  4230. sortBy: sortBy$1,
  4231. timeout,
  4232. times,
  4233. timesLimit,
  4234. timesSeries,
  4235. transform,
  4236. tryEach: tryEach$1,
  4237. unmemoize,
  4238. until,
  4239. waterfall: waterfall$1,
  4240. whilst: whilst$1,
  4241. // aliases
  4242. all: every$1,
  4243. allLimit: everyLimit$1,
  4244. allSeries: everySeries$1,
  4245. any: some$1,
  4246. anyLimit: someLimit$1,
  4247. anySeries: someSeries$1,
  4248. find: detect$1,
  4249. findLimit: detectLimit$1,
  4250. findSeries: detectSeries$1,
  4251. forEach: each,
  4252. forEachSeries: eachSeries$1,
  4253. forEachLimit: eachLimit$2,
  4254. forEachOf: eachOf$1,
  4255. forEachOfSeries: eachOfSeries$1,
  4256. forEachOfLimit: eachOfLimit$2,
  4257. inject: reduce$1,
  4258. foldl: reduce$1,
  4259. foldr: reduceRight,
  4260. select: filter$1,
  4261. selectLimit: filterLimit$1,
  4262. selectSeries: filterSeries$1,
  4263. wrapSync: asyncify,
  4264. during: whilst$1,
  4265. doDuring: doWhilst$1
  4266. };
  4267. exports.default = index;
  4268. exports.apply = apply;
  4269. exports.applyEach = applyEach$1;
  4270. exports.applyEachSeries = applyEachSeries;
  4271. exports.asyncify = asyncify;
  4272. exports.auto = auto;
  4273. exports.autoInject = autoInject;
  4274. exports.cargo = cargo;
  4275. exports.cargoQueue = cargo$1;
  4276. exports.compose = compose;
  4277. exports.concat = concat$1;
  4278. exports.concatLimit = concatLimit$1;
  4279. exports.concatSeries = concatSeries$1;
  4280. exports.constant = constant;
  4281. exports.detect = detect$1;
  4282. exports.detectLimit = detectLimit$1;
  4283. exports.detectSeries = detectSeries$1;
  4284. exports.dir = dir;
  4285. exports.doUntil = doUntil;
  4286. exports.doWhilst = doWhilst$1;
  4287. exports.each = each;
  4288. exports.eachLimit = eachLimit$2;
  4289. exports.eachOf = eachOf$1;
  4290. exports.eachOfLimit = eachOfLimit$2;
  4291. exports.eachOfSeries = eachOfSeries$1;
  4292. exports.eachSeries = eachSeries$1;
  4293. exports.ensureAsync = ensureAsync;
  4294. exports.every = every$1;
  4295. exports.everyLimit = everyLimit$1;
  4296. exports.everySeries = everySeries$1;
  4297. exports.filter = filter$1;
  4298. exports.filterLimit = filterLimit$1;
  4299. exports.filterSeries = filterSeries$1;
  4300. exports.forever = forever$1;
  4301. exports.groupBy = groupBy;
  4302. exports.groupByLimit = groupByLimit$1;
  4303. exports.groupBySeries = groupBySeries;
  4304. exports.log = log;
  4305. exports.map = map$1;
  4306. exports.mapLimit = mapLimit$1;
  4307. exports.mapSeries = mapSeries$1;
  4308. exports.mapValues = mapValues;
  4309. exports.mapValuesLimit = mapValuesLimit$1;
  4310. exports.mapValuesSeries = mapValuesSeries;
  4311. exports.memoize = memoize;
  4312. exports.nextTick = nextTick;
  4313. exports.parallel = parallel;
  4314. exports.parallelLimit = parallelLimit;
  4315. exports.priorityQueue = priorityQueue;
  4316. exports.queue = queue$1;
  4317. exports.race = race$1;
  4318. exports.reduce = reduce$1;
  4319. exports.reduceRight = reduceRight;
  4320. exports.reflect = reflect;
  4321. exports.reflectAll = reflectAll;
  4322. exports.reject = reject$2;
  4323. exports.rejectLimit = rejectLimit$1;
  4324. exports.rejectSeries = rejectSeries$1;
  4325. exports.retry = retry;
  4326. exports.retryable = retryable;
  4327. exports.seq = seq;
  4328. exports.series = series;
  4329. exports.setImmediate = setImmediate$1;
  4330. exports.some = some$1;
  4331. exports.someLimit = someLimit$1;
  4332. exports.someSeries = someSeries$1;
  4333. exports.sortBy = sortBy$1;
  4334. exports.timeout = timeout;
  4335. exports.times = times;
  4336. exports.timesLimit = timesLimit;
  4337. exports.timesSeries = timesSeries;
  4338. exports.transform = transform;
  4339. exports.tryEach = tryEach$1;
  4340. exports.unmemoize = unmemoize;
  4341. exports.until = until;
  4342. exports.waterfall = waterfall$1;
  4343. exports.whilst = whilst$1;
  4344. exports.all = every$1;
  4345. exports.allLimit = everyLimit$1;
  4346. exports.allSeries = everySeries$1;
  4347. exports.any = some$1;
  4348. exports.anyLimit = someLimit$1;
  4349. exports.anySeries = someSeries$1;
  4350. exports.find = detect$1;
  4351. exports.findLimit = detectLimit$1;
  4352. exports.findSeries = detectSeries$1;
  4353. exports.forEach = each;
  4354. exports.forEachSeries = eachSeries$1;
  4355. exports.forEachLimit = eachLimit$2;
  4356. exports.forEachOf = eachOf$1;
  4357. exports.forEachOfSeries = eachOfSeries$1;
  4358. exports.forEachOfLimit = eachOfLimit$2;
  4359. exports.inject = reduce$1;
  4360. exports.foldl = reduce$1;
  4361. exports.foldr = reduceRight;
  4362. exports.select = filter$1;
  4363. exports.selectLimit = filterLimit$1;
  4364. exports.selectSeries = filterSeries$1;
  4365. exports.wrapSync = asyncify;
  4366. exports.during = whilst$1;
  4367. exports.doDuring = doWhilst$1;
  4368. Object.defineProperty(exports, '__esModule', { value: true });
  4369. })));