async.js 179 KB

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