async.mjs 195 KB

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