async.js 220 KB

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