async.js 180 KB

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