async.mjs 196 KB

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