async.js 176 KB

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