async.mjs 196 KB

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