async.mjs 161 KB

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