async.js 172 KB

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