async.js 180 KB

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