Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

async.mjs 161KB

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