async.js 219 KB

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