async.js 180 KB

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