async.js 219 KB

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