async.js 181 KB

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