async.js 179 KB

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