async.mjs 196 KB

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