async.js 220 KB

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