promise.js 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404
  1. // Licensed to the Software Freedom Conservancy (SFC) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The SFC licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. /**
  18. * @fileoverview
  19. *
  20. * > ### IMPORTANT NOTICE
  21. * >
  22. * > The promise manager contained in this module is in the process of being
  23. * > phased out in favor of native JavaScript promises. This will be a long
  24. * > process and will not be completed until there have been two major LTS Node
  25. * > releases (approx. Node v10.0) that support
  26. * > [async functions](https://tc39.github.io/ecmascript-asyncawait/).
  27. * >
  28. * > At this time, the promise manager can be disabled by setting an environment
  29. * > variable, `SELENIUM_PROMISE_MANAGER=0`. In the absence of async functions,
  30. * > users may use generators with the
  31. * > {@link ./promise.consume promise.consume()} function to write "synchronous"
  32. * > style tests:
  33. * >
  34. * > ```js
  35. * > const {Builder, By, Key, promise, until} = require('selenium-webdriver');
  36. * >
  37. * > let result = promise.consume(function* doGoogleSearch() {
  38. * > let driver = new Builder().forBrowser('firefox').build();
  39. * > yield driver.get('http://www.google.com/ncr');
  40. * > yield driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN);
  41. * > yield driver.wait(until.titleIs('webdriver - Google Search'), 1000);
  42. * > yield driver.quit();
  43. * > });
  44. * >
  45. * > result.then(_ => console.log('SUCCESS!'),
  46. * > e => console.error('FAILURE: ' + e));
  47. * > ```
  48. * >
  49. * > The motivation behind this change and full deprecation plan are documented
  50. * > in [issue 2969](https://github.com/SeleniumHQ/selenium/issues/2969).
  51. * >
  52. * >
  53. *
  54. * The promise module is centered around the {@linkplain ControlFlow}, a class
  55. * that coordinates the execution of asynchronous tasks. The ControlFlow allows
  56. * users to focus on the imperative commands for their script without worrying
  57. * about chaining together every single asynchronous action, which can be
  58. * tedious and verbose. APIs may be layered on top of the control flow to read
  59. * as if they were synchronous. For instance, the core
  60. * {@linkplain ./webdriver.WebDriver WebDriver} API is built on top of the
  61. * control flow, allowing users to write
  62. *
  63. * driver.get('http://www.google.com/ncr');
  64. * driver.findElement({name: 'q'}).sendKeys('webdriver', Key.RETURN);
  65. *
  66. * instead of
  67. *
  68. * driver.get('http://www.google.com/ncr')
  69. * .then(function() {
  70. * return driver.findElement({name: 'q'});
  71. * })
  72. * .then(function(q) {
  73. * return q.sendKeys('webdriver', Key.RETURN);
  74. * });
  75. *
  76. * ## Tasks and Task Queues
  77. *
  78. * The control flow is based on the concept of tasks and task queues. Tasks are
  79. * functions that define the basic unit of work for the control flow to execute.
  80. * Each task is scheduled via {@link ControlFlow#execute()}, which will return
  81. * a {@link ManagedPromise} that will be resolved with the task's result.
  82. *
  83. * A task queue contains all of the tasks scheduled within a single turn of the
  84. * [JavaScript event loop][JSEL]. The control flow will create a new task queue
  85. * the first time a task is scheduled within an event loop.
  86. *
  87. * var flow = promise.controlFlow();
  88. * flow.execute(foo); // Creates a new task queue and inserts foo.
  89. * flow.execute(bar); // Inserts bar into the same queue as foo.
  90. * setTimeout(function() {
  91. * flow.execute(baz); // Creates a new task queue and inserts baz.
  92. * }, 0);
  93. *
  94. * Whenever the control flow creates a new task queue, it will automatically
  95. * begin executing tasks in the next available turn of the event loop. This
  96. * execution is [scheduled as a microtask][MicrotasksArticle] like e.g. a
  97. * (native) `Promise.then()` callback.
  98. *
  99. * setTimeout(() => console.log('a'));
  100. * Promise.resolve().then(() => console.log('b')); // A native promise.
  101. * flow.execute(() => console.log('c'));
  102. * Promise.resolve().then(() => console.log('d'));
  103. * setTimeout(() => console.log('fin'));
  104. * // b
  105. * // c
  106. * // d
  107. * // a
  108. * // fin
  109. *
  110. * In the example above, b/c/d is logged before a/fin because native promises
  111. * and this module use "microtask" timers, which have a higher priority than
  112. * "macrotasks" like `setTimeout`.
  113. *
  114. * ## Task Execution
  115. *
  116. * Upon creating a task queue, and whenever an existing queue completes a task,
  117. * the control flow will schedule a microtask timer to process any scheduled
  118. * tasks. This ensures no task is ever started within the same turn of the
  119. * JavaScript event loop in which it was scheduled, nor is a task ever started
  120. * within the same turn that another finishes.
  121. *
  122. * When the execution timer fires, a single task will be dequeued and executed.
  123. * There are several important events that may occur while executing a task
  124. * function:
  125. *
  126. * 1. A new task queue is created by a call to {@link ControlFlow#execute()}.
  127. * Any tasks scheduled within this task queue are considered subtasks of the
  128. * current task.
  129. * 2. The task function throws an error. Any scheduled tasks are immediately
  130. * discarded and the task's promised result (previously returned by
  131. * {@link ControlFlow#execute()}) is immediately rejected with the thrown
  132. * error.
  133. * 3. The task function returns successfully.
  134. *
  135. * If a task function created a new task queue, the control flow will wait for
  136. * that queue to complete before processing the task result. If the queue
  137. * completes without error, the flow will settle the task's promise with the
  138. * value originally returned by the task function. On the other hand, if the task
  139. * queue terminates with an error, the task's promise will be rejected with that
  140. * error.
  141. *
  142. * flow.execute(function() {
  143. * flow.execute(() => console.log('a'));
  144. * flow.execute(() => console.log('b'));
  145. * });
  146. * flow.execute(() => console.log('c'));
  147. * // a
  148. * // b
  149. * // c
  150. *
  151. * ## ManagedPromise Integration
  152. *
  153. * In addition to the {@link ControlFlow} class, the promise module also exports
  154. * a [Promises/A+] {@linkplain ManagedPromise implementation} that is deeply
  155. * integrated with the ControlFlow. First and foremost, each promise
  156. * {@linkplain ManagedPromise#then() callback} is scheduled with the
  157. * control flow as a task. As a result, each callback is invoked in its own turn
  158. * of the JavaScript event loop with its own task queue. If any tasks are
  159. * scheduled within a callback, the callback's promised result will not be
  160. * settled until the task queue has completed.
  161. *
  162. * promise.fulfilled().then(function() {
  163. * flow.execute(function() {
  164. * console.log('b');
  165. * });
  166. * }).then(() => console.log('a'));
  167. * // b
  168. * // a
  169. *
  170. * ### Scheduling ManagedPromise Callbacks <a id="scheduling_callbacks"></a>
  171. *
  172. * How callbacks are scheduled in the control flow depends on when they are
  173. * attached to the promise. Callbacks attached to a _previously_ resolved
  174. * promise are immediately enqueued as subtasks of the currently running task.
  175. *
  176. * var p = promise.fulfilled();
  177. * flow.execute(function() {
  178. * flow.execute(() => console.log('A'));
  179. * p.then( () => console.log('B'));
  180. * flow.execute(() => console.log('C'));
  181. * p.then( () => console.log('D'));
  182. * }).then(function() {
  183. * console.log('fin');
  184. * });
  185. * // A
  186. * // B
  187. * // C
  188. * // D
  189. * // fin
  190. *
  191. * When a promise is resolved while a task function is on the call stack, any
  192. * callbacks also registered in that stack frame are scheduled as if the promise
  193. * were already resolved:
  194. *
  195. * var d = promise.defer();
  196. * flow.execute(function() {
  197. * flow.execute( () => console.log('A'));
  198. * d.promise.then(() => console.log('B'));
  199. * flow.execute( () => console.log('C'));
  200. * d.promise.then(() => console.log('D'));
  201. *
  202. * d.fulfill();
  203. * }).then(function() {
  204. * console.log('fin');
  205. * });
  206. * // A
  207. * // B
  208. * // C
  209. * // D
  210. * // fin
  211. *
  212. * Callbacks attached to an _unresolved_ promise within a task function are
  213. * only weakly scheduled as subtasks and will be dropped if they reach the
  214. * front of the queue before the promise is resolved. In the example below, the
  215. * callbacks for `B` & `D` are dropped as sub-tasks since they are attached to
  216. * an unresolved promise when they reach the front of the task queue.
  217. *
  218. * var d = promise.defer();
  219. * flow.execute(function() {
  220. * flow.execute( () => console.log('A'));
  221. * d.promise.then(() => console.log('B'));
  222. * flow.execute( () => console.log('C'));
  223. * d.promise.then(() => console.log('D'));
  224. *
  225. * setTimeout(d.fulfill, 20);
  226. * }).then(function() {
  227. * console.log('fin')
  228. * });
  229. * // A
  230. * // C
  231. * // fin
  232. * // B
  233. * // D
  234. *
  235. * If a promise is resolved while a task function is on the call stack, any
  236. * previously registered and unqueued callbacks (i.e. either attached while no
  237. * task was on the call stack, or previously dropped as described above) act as
  238. * _interrupts_ and are inserted at the front of the task queue. If multiple
  239. * promises are fulfilled, their interrupts are enqueued in the order the
  240. * promises are resolved.
  241. *
  242. * var d1 = promise.defer();
  243. * d1.promise.then(() => console.log('A'));
  244. *
  245. * var d2 = promise.defer();
  246. * d2.promise.then(() => console.log('B'));
  247. *
  248. * flow.execute(function() {
  249. * d1.promise.then(() => console.log('C'));
  250. * flow.execute(() => console.log('D'));
  251. * });
  252. * flow.execute(function() {
  253. * flow.execute(() => console.log('E'));
  254. * flow.execute(() => console.log('F'));
  255. * d1.fulfill();
  256. * d2.fulfill();
  257. * }).then(function() {
  258. * console.log('fin');
  259. * });
  260. * // D
  261. * // A
  262. * // C
  263. * // B
  264. * // E
  265. * // F
  266. * // fin
  267. *
  268. * Within a task function (or callback), each step of a promise chain acts as
  269. * an interrupt on the task queue:
  270. *
  271. * var d = promise.defer();
  272. * flow.execute(function() {
  273. * d.promise.
  274. * then(() => console.log('A')).
  275. * then(() => console.log('B')).
  276. * then(() => console.log('C')).
  277. * then(() => console.log('D'));
  278. *
  279. * flow.execute(() => console.log('E'));
  280. * d.fulfill();
  281. * }).then(function() {
  282. * console.log('fin');
  283. * });
  284. * // A
  285. * // B
  286. * // C
  287. * // D
  288. * // E
  289. * // fin
  290. *
  291. * If there are multiple promise chains derived from a single promise, they are
  292. * processed in the order created:
  293. *
  294. * var d = promise.defer();
  295. * flow.execute(function() {
  296. * var chain = d.promise.then(() => console.log('A'));
  297. *
  298. * chain.then(() => console.log('B')).
  299. * then(() => console.log('C'));
  300. *
  301. * chain.then(() => console.log('D')).
  302. * then(() => console.log('E'));
  303. *
  304. * flow.execute(() => console.log('F'));
  305. *
  306. * d.fulfill();
  307. * }).then(function() {
  308. * console.log('fin');
  309. * });
  310. * // A
  311. * // B
  312. * // C
  313. * // D
  314. * // E
  315. * // F
  316. * // fin
  317. *
  318. * Even though a subtask's promised result will never resolve while the task
  319. * function is on the stack, it will be treated as a promise resolved within the
  320. * task. In all other scenarios, a task's promise behaves just like a normal
  321. * promise. In the sample below, `C/D` is logged before `B` because the
  322. * resolution of `subtask1` interrupts the flow of the enclosing task. Within
  323. * the final subtask, `E/F` is logged in order because `subtask1` is a resolved
  324. * promise when that task runs.
  325. *
  326. * flow.execute(function() {
  327. * var subtask1 = flow.execute(() => console.log('A'));
  328. * var subtask2 = flow.execute(() => console.log('B'));
  329. *
  330. * subtask1.then(() => console.log('C'));
  331. * subtask1.then(() => console.log('D'));
  332. *
  333. * flow.execute(function() {
  334. * flow.execute(() => console.log('E'));
  335. * subtask1.then(() => console.log('F'));
  336. * });
  337. * }).then(function() {
  338. * console.log('fin');
  339. * });
  340. * // A
  341. * // C
  342. * // D
  343. * // B
  344. * // E
  345. * // F
  346. * // fin
  347. *
  348. * Finally, consider the following:
  349. *
  350. * var d = promise.defer();
  351. * d.promise.then(() => console.log('A'));
  352. * d.promise.then(() => console.log('B'));
  353. *
  354. * flow.execute(function() {
  355. * flow.execute( () => console.log('C'));
  356. * d.promise.then(() => console.log('D'));
  357. *
  358. * flow.execute( () => console.log('E'));
  359. * d.promise.then(() => console.log('F'));
  360. *
  361. * d.fulfill();
  362. *
  363. * flow.execute( () => console.log('G'));
  364. * d.promise.then(() => console.log('H'));
  365. * }).then(function() {
  366. * console.log('fin');
  367. * });
  368. * // A
  369. * // B
  370. * // C
  371. * // D
  372. * // E
  373. * // F
  374. * // G
  375. * // H
  376. * // fin
  377. *
  378. * In this example, callbacks are registered on `d.promise` both before and
  379. * during the invocation of the task function. When `d.fulfill()` is called,
  380. * the callbacks registered before the task (`A` & `B`) are registered as
  381. * interrupts. The remaining callbacks were all attached within the task and
  382. * are scheduled in the flow as standard tasks.
  383. *
  384. * ## Generator Support
  385. *
  386. * [Generators][GF] may be scheduled as tasks within a control flow or attached
  387. * as callbacks to a promise. Each time the generator yields a promise, the
  388. * control flow will wait for that promise to settle before executing the next
  389. * iteration of the generator. The yielded promise's fulfilled value will be
  390. * passed back into the generator:
  391. *
  392. * flow.execute(function* () {
  393. * var d = promise.defer();
  394. *
  395. * setTimeout(() => console.log('...waiting...'), 25);
  396. * setTimeout(() => d.fulfill(123), 50);
  397. *
  398. * console.log('start: ' + Date.now());
  399. *
  400. * var value = yield d.promise;
  401. * console.log('mid: %d; value = %d', Date.now(), value);
  402. *
  403. * yield promise.delayed(10);
  404. * console.log('end: ' + Date.now());
  405. * }).then(function() {
  406. * console.log('fin');
  407. * });
  408. * // start: 0
  409. * // ...waiting...
  410. * // mid: 50; value = 123
  411. * // end: 60
  412. * // fin
  413. *
  414. * Yielding the result of a promise chain will wait for the entire chain to
  415. * complete:
  416. *
  417. * promise.fulfilled().then(function* () {
  418. * console.log('start: ' + Date.now());
  419. *
  420. * var value = yield flow.
  421. * execute(() => console.log('A')).
  422. * then( () => console.log('B')).
  423. * then( () => 123);
  424. *
  425. * console.log('mid: %s; value = %d', Date.now(), value);
  426. *
  427. * yield flow.execute(() => console.log('C'));
  428. * }).then(function() {
  429. * console.log('fin');
  430. * });
  431. * // start: 0
  432. * // A
  433. * // B
  434. * // mid: 2; value = 123
  435. * // C
  436. * // fin
  437. *
  438. * Yielding a _rejected_ promise will cause the rejected value to be thrown
  439. * within the generator function:
  440. *
  441. * flow.execute(function* () {
  442. * console.log('start: ' + Date.now());
  443. * try {
  444. * yield promise.delayed(10).then(function() {
  445. * throw Error('boom');
  446. * });
  447. * } catch (ex) {
  448. * console.log('caught time: ' + Date.now());
  449. * console.log(ex.message);
  450. * }
  451. * });
  452. * // start: 0
  453. * // caught time: 10
  454. * // boom
  455. *
  456. * # Error Handling
  457. *
  458. * ES6 promises do not require users to handle a promise rejections. This can
  459. * result in subtle bugs as the rejections are silently "swallowed" by the
  460. * Promise class.
  461. *
  462. * Promise.reject(Error('boom'));
  463. * // ... *crickets* ...
  464. *
  465. * Selenium's promise module, on the other hand, requires that every rejection
  466. * be explicitly handled. When a {@linkplain ManagedPromise ManagedPromise} is
  467. * rejected and no callbacks are defined on that promise, it is considered an
  468. * _unhandled rejection_ and reported to the active task queue. If the rejection
  469. * remains unhandled after a single turn of the [event loop][JSEL] (scheduled
  470. * with a microtask), it will propagate up the stack.
  471. *
  472. * ## Error Propagation
  473. *
  474. * If an unhandled rejection occurs within a task function, that task's promised
  475. * result is rejected and all remaining subtasks are discarded:
  476. *
  477. * flow.execute(function() {
  478. * // No callbacks registered on promise -> unhandled rejection
  479. * promise.rejected(Error('boom'));
  480. * flow.execute(function() { console.log('this will never run'); });
  481. * }).catch(function(e) {
  482. * console.log(e.message);
  483. * });
  484. * // boom
  485. *
  486. * The promised results for discarded tasks are silently rejected with a
  487. * cancellation error and existing callback chains will never fire.
  488. *
  489. * flow.execute(function() {
  490. * promise.rejected(Error('boom'));
  491. * flow.execute(function() { console.log('a'); }).
  492. * then(function() { console.log('b'); });
  493. * }).catch(function(e) {
  494. * console.log(e.message);
  495. * });
  496. * // boom
  497. *
  498. * An unhandled rejection takes precedence over a task function's returned
  499. * result, even if that value is another promise:
  500. *
  501. * flow.execute(function() {
  502. * promise.rejected(Error('boom'));
  503. * return flow.execute(someOtherTask);
  504. * }).catch(function(e) {
  505. * console.log(e.message);
  506. * });
  507. * // boom
  508. *
  509. * If there are multiple unhandled rejections within a task, they are packaged
  510. * in a {@link MultipleUnhandledRejectionError}, which has an `errors` property
  511. * that is a `Set` of the recorded unhandled rejections:
  512. *
  513. * flow.execute(function() {
  514. * promise.rejected(Error('boom1'));
  515. * promise.rejected(Error('boom2'));
  516. * }).catch(function(ex) {
  517. * console.log(ex instanceof MultipleUnhandledRejectionError);
  518. * for (var e of ex.errors) {
  519. * console.log(e.message);
  520. * }
  521. * });
  522. * // boom1
  523. * // boom2
  524. *
  525. * When a subtask is discarded due to an unreported rejection in its parent
  526. * frame, the existing callbacks on that task will never settle and the
  527. * callbacks will not be invoked. If a new callback is attached to the subtask
  528. * _after_ it has been discarded, it is handled the same as adding a callback
  529. * to a cancelled promise: the error-callback path is invoked. This behavior is
  530. * intended to handle cases where the user saves a reference to a task promise,
  531. * as illustrated below.
  532. *
  533. * var subTask;
  534. * flow.execute(function() {
  535. * promise.rejected(Error('boom'));
  536. * subTask = flow.execute(function() {});
  537. * }).catch(function(e) {
  538. * console.log(e.message);
  539. * }).then(function() {
  540. * return subTask.then(
  541. * () => console.log('subtask success!'),
  542. * (e) => console.log('subtask failed:\n' + e));
  543. * });
  544. * // boom
  545. * // subtask failed:
  546. * // DiscardedTaskError: Task was discarded due to a previous failure: boom
  547. *
  548. * When a subtask fails, its promised result is treated the same as any other
  549. * promise: it must be handled within one turn of the rejection or the unhandled
  550. * rejection is propagated to the parent task. This means users can catch errors
  551. * from complex flows from the top level task:
  552. *
  553. * flow.execute(function() {
  554. * flow.execute(function() {
  555. * flow.execute(function() {
  556. * throw Error('fail!');
  557. * });
  558. * });
  559. * }).catch(function(e) {
  560. * console.log(e.message);
  561. * });
  562. * // fail!
  563. *
  564. * ## Unhandled Rejection Events
  565. *
  566. * When an unhandled rejection propagates to the root of the control flow, the
  567. * flow will emit an __uncaughtException__ event. If no listeners are registered
  568. * on the flow, the error will be rethrown to the global error handler: an
  569. * __uncaughtException__ event from the
  570. * [`process`](https://nodejs.org/api/process.html) object in node, or
  571. * `window.onerror` when running in a browser.
  572. *
  573. * Bottom line: you __*must*__ handle rejected promises.
  574. *
  575. * # Promises/A+ Compatibility
  576. *
  577. * This `promise` module is compliant with the [Promises/A+] specification
  578. * except for sections `2.2.6.1` and `2.2.6.2`:
  579. *
  580. * >
  581. * > - `then` may be called multiple times on the same promise.
  582. * > - If/when `promise` is fulfilled, all respective `onFulfilled` callbacks
  583. * > must execute in the order of their originating calls to `then`.
  584. * > - If/when `promise` is rejected, all respective `onRejected` callbacks
  585. * > must execute in the order of their originating calls to `then`.
  586. * >
  587. *
  588. * Specifically, the conformance tests contain the following scenario (for
  589. * brevity, only the fulfillment version is shown):
  590. *
  591. * var p1 = Promise.resolve();
  592. * p1.then(function() {
  593. * console.log('A');
  594. * p1.then(() => console.log('B'));
  595. * });
  596. * p1.then(() => console.log('C'));
  597. * // A
  598. * // C
  599. * // B
  600. *
  601. * Since the [ControlFlow](#scheduling_callbacks) executes promise callbacks as
  602. * tasks, with this module, the result would be:
  603. *
  604. * var p2 = promise.fulfilled();
  605. * p2.then(function() {
  606. * console.log('A');
  607. * p2.then(() => console.log('B');
  608. * });
  609. * p2.then(() => console.log('C'));
  610. * // A
  611. * // B
  612. * // C
  613. *
  614. * [JSEL]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
  615. * [GF]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
  616. * [Promises/A+]: https://promisesaplus.com/
  617. * [MicrotasksArticle]: https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
  618. */
  619. 'use strict';
  620. const error = require('./error');
  621. const events = require('./events');
  622. const logging = require('./logging');
  623. /**
  624. * Alias to help with readability and differentiate types.
  625. * @const
  626. */
  627. const NativePromise = Promise;
  628. /**
  629. * Whether to append traces of `then` to rejection errors.
  630. * @type {boolean}
  631. */
  632. var LONG_STACK_TRACES = false; // TODO: this should not be CONSTANT_CASE
  633. /** @const */
  634. const LOG = logging.getLogger('promise');
  635. const UNIQUE_IDS = new WeakMap;
  636. let nextId = 1;
  637. function getUid(obj) {
  638. let id = UNIQUE_IDS.get(obj);
  639. if (!id) {
  640. id = nextId;
  641. nextId += 1;
  642. UNIQUE_IDS.set(obj, id);
  643. }
  644. return id;
  645. }
  646. /**
  647. * Runs the given function after a microtask yield.
  648. * @param {function()} fn The function to run.
  649. */
  650. function asyncRun(fn) {
  651. NativePromise.resolve().then(function() {
  652. try {
  653. fn();
  654. } catch (ignored) {
  655. // Do nothing.
  656. }
  657. });
  658. }
  659. /**
  660. * @param {number} level What level of verbosity to log with.
  661. * @param {(string|function(this: T): string)} loggable The message to log.
  662. * @param {T=} opt_self The object in whose context to run the loggable
  663. * function.
  664. * @template T
  665. */
  666. function vlog(level, loggable, opt_self) {
  667. var logLevel = logging.Level.FINE;
  668. if (level > 1) {
  669. logLevel = logging.Level.FINEST;
  670. } else if (level > 0) {
  671. logLevel = logging.Level.FINER;
  672. }
  673. if (typeof loggable === 'function') {
  674. loggable = loggable.bind(opt_self);
  675. }
  676. LOG.log(logLevel, loggable);
  677. }
  678. /**
  679. * Generates an error to capture the current stack trace.
  680. * @param {string} name Error name for this stack trace.
  681. * @param {string} msg Message to record.
  682. * @param {Function=} opt_topFn The function that should appear at the top of
  683. * the stack; only applicable in V8.
  684. * @return {!Error} The generated error.
  685. */
  686. function captureStackTrace(name, msg, opt_topFn) {
  687. var e = Error(msg);
  688. e.name = name;
  689. if (Error.captureStackTrace) {
  690. Error.captureStackTrace(e, opt_topFn);
  691. } else {
  692. var stack = Error().stack;
  693. if (stack) {
  694. e.stack = e.toString();
  695. e.stack += '\n' + stack;
  696. }
  697. }
  698. return e;
  699. }
  700. /**
  701. * Error used when the computation of a promise is cancelled.
  702. */
  703. class CancellationError extends Error {
  704. /**
  705. * @param {string=} opt_msg The cancellation message.
  706. */
  707. constructor(opt_msg) {
  708. super(opt_msg);
  709. /** @override */
  710. this.name = this.constructor.name;
  711. /** @private {boolean} */
  712. this.silent_ = false;
  713. }
  714. /**
  715. * Wraps the given error in a CancellationError.
  716. *
  717. * @param {*} error The error to wrap.
  718. * @param {string=} opt_msg The prefix message to use.
  719. * @return {!CancellationError} A cancellation error.
  720. */
  721. static wrap(error, opt_msg) {
  722. var message;
  723. if (error instanceof CancellationError) {
  724. return new CancellationError(
  725. opt_msg ? (opt_msg + ': ' + error.message) : error.message);
  726. } else if (opt_msg) {
  727. message = opt_msg;
  728. if (error) {
  729. message += ': ' + error;
  730. }
  731. return new CancellationError(message);
  732. }
  733. if (error) {
  734. message = error + '';
  735. }
  736. return new CancellationError(message);
  737. }
  738. }
  739. /**
  740. * Error used to cancel tasks when a control flow is reset.
  741. * @final
  742. */
  743. class FlowResetError extends CancellationError {
  744. constructor() {
  745. super('ControlFlow was reset');
  746. this.silent_ = true;
  747. }
  748. }
  749. /**
  750. * Error used to cancel tasks that have been discarded due to an uncaught error
  751. * reported earlier in the control flow.
  752. * @final
  753. */
  754. class DiscardedTaskError extends CancellationError {
  755. /** @param {*} error The original error. */
  756. constructor(error) {
  757. if (error instanceof DiscardedTaskError) {
  758. return /** @type {!DiscardedTaskError} */(error);
  759. }
  760. var msg = '';
  761. if (error) {
  762. msg = ': ' + (
  763. typeof error.message === 'string' ? error.message : error);
  764. }
  765. super('Task was discarded due to a previous failure' + msg);
  766. this.silent_ = true;
  767. }
  768. }
  769. /**
  770. * Error used when there are multiple unhandled promise rejections detected
  771. * within a task or callback.
  772. *
  773. * @final
  774. */
  775. class MultipleUnhandledRejectionError extends Error {
  776. /**
  777. * @param {!(Set<*>)} errors The errors to report.
  778. */
  779. constructor(errors) {
  780. super('Multiple unhandled promise rejections reported');
  781. /** @override */
  782. this.name = this.constructor.name;
  783. /** @type {!Set<*>} */
  784. this.errors = errors;
  785. }
  786. }
  787. /**
  788. * Property used to flag constructor's as implementing the Thenable interface
  789. * for runtime type checking.
  790. * @const
  791. */
  792. const IMPLEMENTED_BY_SYMBOL = Symbol('promise.Thenable');
  793. const CANCELLABLE_SYMBOL = Symbol('promise.CancellableThenable');
  794. /**
  795. * @param {function(new: ?)} ctor
  796. * @param {!Object} symbol
  797. */
  798. function addMarkerSymbol(ctor, symbol) {
  799. try {
  800. ctor.prototype[symbol] = true;
  801. } catch (ignored) {
  802. // Property access denied?
  803. }
  804. }
  805. /**
  806. * @param {*} object
  807. * @param {!Object} symbol
  808. * @return {boolean}
  809. */
  810. function hasMarkerSymbol(object, symbol) {
  811. if (!object) {
  812. return false;
  813. }
  814. try {
  815. return !!object[symbol];
  816. } catch (e) {
  817. return false; // Property access seems to be forbidden.
  818. }
  819. }
  820. /**
  821. * Thenable is a promise-like object with a {@code then} method which may be
  822. * used to schedule callbacks on a promised value.
  823. *
  824. * @record
  825. * @extends {IThenable<T>}
  826. * @template T
  827. */
  828. class Thenable {
  829. /**
  830. * Adds a property to a class prototype to allow runtime checks of whether
  831. * instances of that class implement the Thenable interface.
  832. * @param {function(new: Thenable, ...?)} ctor The
  833. * constructor whose prototype to modify.
  834. */
  835. static addImplementation(ctor) {
  836. addMarkerSymbol(ctor, IMPLEMENTED_BY_SYMBOL);
  837. }
  838. /**
  839. * Checks if an object has been tagged for implementing the Thenable
  840. * interface as defined by {@link Thenable.addImplementation}.
  841. * @param {*} object The object to test.
  842. * @return {boolean} Whether the object is an implementation of the Thenable
  843. * interface.
  844. */
  845. static isImplementation(object) {
  846. return hasMarkerSymbol(object, IMPLEMENTED_BY_SYMBOL);
  847. }
  848. /**
  849. * Registers listeners for when this instance is resolved.
  850. *
  851. * @param {?(function(T): (R|IThenable<R>))=} opt_callback The
  852. * function to call if this promise is successfully resolved. The function
  853. * should expect a single argument: the promise's resolved value.
  854. * @param {?(function(*): (R|IThenable<R>))=} opt_errback
  855. * The function to call if this promise is rejected. The function should
  856. * expect a single argument: the rejection reason.
  857. * @return {!Thenable<R>} A new promise which will be resolved with the result
  858. * of the invoked callback.
  859. * @template R
  860. */
  861. then(opt_callback, opt_errback) {}
  862. /**
  863. * Registers a listener for when this promise is rejected. This is synonymous
  864. * with the {@code catch} clause in a synchronous API:
  865. *
  866. * // Synchronous API:
  867. * try {
  868. * doSynchronousWork();
  869. * } catch (ex) {
  870. * console.error(ex);
  871. * }
  872. *
  873. * // Asynchronous promise API:
  874. * doAsynchronousWork().catch(function(ex) {
  875. * console.error(ex);
  876. * });
  877. *
  878. * @param {function(*): (R|IThenable<R>)} errback The
  879. * function to call if this promise is rejected. The function should
  880. * expect a single argument: the rejection reason.
  881. * @return {!Thenable<R>} A new promise which will be resolved with the result
  882. * of the invoked callback.
  883. * @template R
  884. */
  885. catch(errback) {}
  886. }
  887. /**
  888. * Marker interface for objects that allow consumers to request the cancellation
  889. * of a promise-based operation. A cancelled promise will be rejected with a
  890. * {@link CancellationError}.
  891. *
  892. * This interface is considered package-private and should not be used outside
  893. * of selenium-webdriver.
  894. *
  895. * @interface
  896. * @extends {Thenable<T>}
  897. * @template T
  898. * @package
  899. */
  900. class CancellableThenable {
  901. /**
  902. * @param {function(new: CancellableThenable, ...?)} ctor
  903. */
  904. static addImplementation(ctor) {
  905. Thenable.addImplementation(ctor);
  906. addMarkerSymbol(ctor, CANCELLABLE_SYMBOL);
  907. }
  908. /**
  909. * @param {*} object
  910. * @return {boolean}
  911. */
  912. static isImplementation(object) {
  913. return hasMarkerSymbol(object, CANCELLABLE_SYMBOL);
  914. }
  915. /**
  916. * Requests the cancellation of the computation of this promise's value,
  917. * rejecting the promise in the process. This method is a no-op if the promise
  918. * has already been resolved.
  919. *
  920. * @param {(string|Error)=} opt_reason The reason this promise is being
  921. * cancelled. This value will be wrapped in a {@link CancellationError}.
  922. */
  923. cancel(opt_reason) {}
  924. }
  925. /**
  926. * @enum {string}
  927. */
  928. const PromiseState = {
  929. PENDING: 'pending',
  930. BLOCKED: 'blocked',
  931. REJECTED: 'rejected',
  932. FULFILLED: 'fulfilled'
  933. };
  934. /**
  935. * Internal map used to store cancellation handlers for {@link ManagedPromise}
  936. * objects. This is an internal implementation detail used by the
  937. * {@link TaskQueue} class to monitor for when a promise is cancelled without
  938. * generating an extra promise via then().
  939. *
  940. * @const {!WeakMap<!ManagedPromise, function(!CancellationError)>}
  941. */
  942. const ON_CANCEL_HANDLER = new WeakMap;
  943. const SKIP_LOG = Symbol('skip-log');
  944. const FLOW_LOG = logging.getLogger('promise.ControlFlow');
  945. /**
  946. * Represents the eventual value of a completed operation. Each promise may be
  947. * in one of three states: pending, fulfilled, or rejected. Each promise starts
  948. * in the pending state and may make a single transition to either a
  949. * fulfilled or rejected state, at which point the promise is considered
  950. * resolved.
  951. *
  952. * @implements {CancellableThenable<T>}
  953. * @template T
  954. * @see http://promises-aplus.github.io/promises-spec/
  955. */
  956. class ManagedPromise {
  957. /**
  958. * @param {function(
  959. * function((T|IThenable<T>|Thenable)=),
  960. * function(*=))} resolver
  961. * Function that is invoked immediately to begin computation of this
  962. * promise's value. The function should accept a pair of callback
  963. * functions, one for fulfilling the promise and another for rejecting it.
  964. * @param {ControlFlow=} opt_flow The control flow
  965. * this instance was created under. Defaults to the currently active flow.
  966. * @param {?=} opt_skipLog An internal parameter used to skip logging the
  967. * creation of this promise. This parameter has no effect unless it is
  968. * strictly equal to an internal symbol. In other words, this parameter
  969. * is always ignored for external code.
  970. */
  971. constructor(resolver, opt_flow, opt_skipLog) {
  972. if (!usePromiseManager()) {
  973. throw TypeError(
  974. 'Unable to create a managed promise instance: the promise manager has'
  975. + ' been disabled by the SELENIUM_PROMISE_MANAGER environment'
  976. + ' variable: ' + process.env['SELENIUM_PROMISE_MANAGER']);
  977. } else if (opt_skipLog !== SKIP_LOG) {
  978. FLOW_LOG.warning(() => {
  979. let e =
  980. captureStackTrace(
  981. 'ManagedPromiseError',
  982. 'Creating a new managed Promise. This call will fail when the'
  983. + ' promise manager is disabled',
  984. ManagedPromise)
  985. return e.stack;
  986. });
  987. }
  988. getUid(this);
  989. /** @private {!ControlFlow} */
  990. this.flow_ = opt_flow || controlFlow();
  991. /** @private {Error} */
  992. this.stack_ = null;
  993. if (LONG_STACK_TRACES) {
  994. this.stack_ = captureStackTrace('ManagedPromise', 'new', this.constructor);
  995. }
  996. /** @private {Thenable<?>} */
  997. this.parent_ = null;
  998. /** @private {Array<!Task>} */
  999. this.callbacks_ = null;
  1000. /** @private {PromiseState} */
  1001. this.state_ = PromiseState.PENDING;
  1002. /** @private {boolean} */
  1003. this.handled_ = false;
  1004. /** @private {*} */
  1005. this.value_ = undefined;
  1006. /** @private {TaskQueue} */
  1007. this.queue_ = null;
  1008. try {
  1009. var self = this;
  1010. resolver(function(value) {
  1011. self.resolve_(PromiseState.FULFILLED, value);
  1012. }, function(reason) {
  1013. self.resolve_(PromiseState.REJECTED, reason);
  1014. });
  1015. } catch (ex) {
  1016. this.resolve_(PromiseState.REJECTED, ex);
  1017. }
  1018. }
  1019. /**
  1020. * Creates a promise that is immediately resolved with the given value.
  1021. *
  1022. * @param {T=} opt_value The value to resolve.
  1023. * @return {!ManagedPromise<T>} A promise resolved with the given value.
  1024. * @template T
  1025. */
  1026. static resolve(opt_value) {
  1027. if (opt_value instanceof ManagedPromise) {
  1028. return opt_value;
  1029. }
  1030. return new ManagedPromise(resolve => resolve(opt_value));
  1031. }
  1032. /**
  1033. * Creates a promise that is immediately rejected with the given reason.
  1034. *
  1035. * @param {*=} opt_reason The rejection reason.
  1036. * @return {!ManagedPromise<?>} A new rejected promise.
  1037. */
  1038. static reject(opt_reason) {
  1039. return new ManagedPromise((_, reject) => reject(opt_reason));
  1040. }
  1041. /** @override */
  1042. toString() {
  1043. return 'ManagedPromise::' + getUid(this) +
  1044. ' {[[PromiseStatus]]: "' + this.state_ + '"}';
  1045. }
  1046. /**
  1047. * Resolves this promise. If the new value is itself a promise, this function
  1048. * will wait for it to be resolved before notifying the registered listeners.
  1049. * @param {PromiseState} newState The promise's new state.
  1050. * @param {*} newValue The promise's new value.
  1051. * @throws {TypeError} If {@code newValue === this}.
  1052. * @private
  1053. */
  1054. resolve_(newState, newValue) {
  1055. if (PromiseState.PENDING !== this.state_) {
  1056. return;
  1057. }
  1058. if (newValue === this) {
  1059. // See promise a+, 2.3.1
  1060. // http://promises-aplus.github.io/promises-spec/#point-48
  1061. newValue = new TypeError('A promise may not resolve to itself');
  1062. newState = PromiseState.REJECTED;
  1063. }
  1064. this.parent_ = null;
  1065. this.state_ = PromiseState.BLOCKED;
  1066. if (newState !== PromiseState.REJECTED) {
  1067. if (Thenable.isImplementation(newValue)) {
  1068. // 2.3.2
  1069. newValue = /** @type {!Thenable} */(newValue);
  1070. this.parent_ = newValue;
  1071. newValue.then(
  1072. this.unblockAndResolve_.bind(this, PromiseState.FULFILLED),
  1073. this.unblockAndResolve_.bind(this, PromiseState.REJECTED));
  1074. return;
  1075. } else if (newValue
  1076. && (typeof newValue === 'object' || typeof newValue === 'function')) {
  1077. // 2.3.3
  1078. try {
  1079. // 2.3.3.1
  1080. var then = newValue['then'];
  1081. } catch (e) {
  1082. // 2.3.3.2
  1083. this.state_ = PromiseState.REJECTED;
  1084. this.value_ = e;
  1085. this.scheduleNotifications_();
  1086. return;
  1087. }
  1088. if (typeof then === 'function') {
  1089. // 2.3.3.3
  1090. this.invokeThen_(/** @type {!Object} */(newValue), then);
  1091. return;
  1092. }
  1093. }
  1094. }
  1095. if (newState === PromiseState.REJECTED &&
  1096. isError(newValue) && newValue.stack && this.stack_) {
  1097. newValue.stack += '\nFrom: ' + (this.stack_.stack || this.stack_);
  1098. }
  1099. // 2.3.3.4 and 2.3.4
  1100. this.state_ = newState;
  1101. this.value_ = newValue;
  1102. this.scheduleNotifications_();
  1103. }
  1104. /**
  1105. * Invokes a thenable's "then" method according to 2.3.3.3 of the promise
  1106. * A+ spec.
  1107. * @param {!Object} x The thenable object.
  1108. * @param {!Function} then The "then" function to invoke.
  1109. * @private
  1110. */
  1111. invokeThen_(x, then) {
  1112. var called = false;
  1113. var self = this;
  1114. var resolvePromise = function(value) {
  1115. if (!called) { // 2.3.3.3.3
  1116. called = true;
  1117. // 2.3.3.3.1
  1118. self.unblockAndResolve_(PromiseState.FULFILLED, value);
  1119. }
  1120. };
  1121. var rejectPromise = function(reason) {
  1122. if (!called) { // 2.3.3.3.3
  1123. called = true;
  1124. // 2.3.3.3.2
  1125. self.unblockAndResolve_(PromiseState.REJECTED, reason);
  1126. }
  1127. };
  1128. try {
  1129. // 2.3.3.3
  1130. then.call(x, resolvePromise, rejectPromise);
  1131. } catch (e) {
  1132. // 2.3.3.3.4.2
  1133. rejectPromise(e);
  1134. }
  1135. }
  1136. /**
  1137. * @param {PromiseState} newState The promise's new state.
  1138. * @param {*} newValue The promise's new value.
  1139. * @private
  1140. */
  1141. unblockAndResolve_(newState, newValue) {
  1142. if (this.state_ === PromiseState.BLOCKED) {
  1143. this.state_ = PromiseState.PENDING;
  1144. this.resolve_(newState, newValue);
  1145. }
  1146. }
  1147. /**
  1148. * @private
  1149. */
  1150. scheduleNotifications_() {
  1151. vlog(2, () => this + ' scheduling notifications', this);
  1152. ON_CANCEL_HANDLER.delete(this);
  1153. if (this.value_ instanceof CancellationError
  1154. && this.value_.silent_) {
  1155. this.callbacks_ = null;
  1156. }
  1157. if (!this.queue_) {
  1158. this.queue_ = this.flow_.getActiveQueue_();
  1159. }
  1160. if (!this.handled_ &&
  1161. this.state_ === PromiseState.REJECTED &&
  1162. !(this.value_ instanceof CancellationError)) {
  1163. this.queue_.addUnhandledRejection(this);
  1164. }
  1165. this.queue_.scheduleCallbacks(this);
  1166. }
  1167. /** @override */
  1168. cancel(opt_reason) {
  1169. if (!canCancel(this)) {
  1170. return;
  1171. }
  1172. if (this.parent_ && canCancel(this.parent_)) {
  1173. /** @type {!CancellableThenable} */(this.parent_).cancel(opt_reason);
  1174. } else {
  1175. var reason = CancellationError.wrap(opt_reason);
  1176. let onCancel = ON_CANCEL_HANDLER.get(this);
  1177. if (onCancel) {
  1178. onCancel(reason);
  1179. ON_CANCEL_HANDLER.delete(this);
  1180. }
  1181. if (this.state_ === PromiseState.BLOCKED) {
  1182. this.unblockAndResolve_(PromiseState.REJECTED, reason);
  1183. } else {
  1184. this.resolve_(PromiseState.REJECTED, reason);
  1185. }
  1186. }
  1187. function canCancel(promise) {
  1188. if (!(promise instanceof ManagedPromise)) {
  1189. return CancellableThenable.isImplementation(promise);
  1190. }
  1191. return promise.state_ === PromiseState.PENDING
  1192. || promise.state_ === PromiseState.BLOCKED;
  1193. }
  1194. }
  1195. /** @override */
  1196. then(opt_callback, opt_errback) {
  1197. return this.addCallback_(
  1198. opt_callback, opt_errback, 'then', ManagedPromise.prototype.then);
  1199. }
  1200. /** @override */
  1201. catch(errback) {
  1202. return this.addCallback_(
  1203. null, errback, 'catch', ManagedPromise.prototype.catch);
  1204. }
  1205. /**
  1206. * @param {function(): (R|IThenable<R>)} callback
  1207. * @return {!ManagedPromise<R>}
  1208. * @template R
  1209. * @see ./promise.finally()
  1210. */
  1211. finally(callback) {
  1212. let result = thenFinally(this, callback);
  1213. return /** @type {!ManagedPromise} */(result);
  1214. }
  1215. /**
  1216. * Registers a new callback with this promise
  1217. * @param {(function(T): (R|IThenable<R>)|null|undefined)} callback The
  1218. * fulfillment callback.
  1219. * @param {(function(*): (R|IThenable<R>)|null|undefined)} errback The
  1220. * rejection callback.
  1221. * @param {string} name The callback name.
  1222. * @param {!Function} fn The function to use as the top of the stack when
  1223. * recording the callback's creation point.
  1224. * @return {!ManagedPromise<R>} A new promise which will be resolved with the
  1225. * result of the invoked callback.
  1226. * @template R
  1227. * @private
  1228. */
  1229. addCallback_(callback, errback, name, fn) {
  1230. if (typeof callback !== 'function' && typeof errback !== 'function') {
  1231. return this;
  1232. }
  1233. this.handled_ = true;
  1234. if (this.queue_) {
  1235. this.queue_.clearUnhandledRejection(this);
  1236. }
  1237. var cb = new Task(
  1238. this.flow_,
  1239. this.invokeCallback_.bind(this, callback, errback),
  1240. name,
  1241. LONG_STACK_TRACES ? {name: 'Promise', top: fn} : undefined);
  1242. cb.promise.parent_ = this;
  1243. if (this.state_ !== PromiseState.PENDING &&
  1244. this.state_ !== PromiseState.BLOCKED) {
  1245. this.flow_.getActiveQueue_().enqueue(cb);
  1246. } else {
  1247. if (!this.callbacks_) {
  1248. this.callbacks_ = [];
  1249. }
  1250. this.callbacks_.push(cb);
  1251. cb.blocked = true;
  1252. this.flow_.getActiveQueue_().enqueue(cb);
  1253. }
  1254. return cb.promise;
  1255. }
  1256. /**
  1257. * Invokes a callback function attached to this promise.
  1258. * @param {(function(T): (R|IThenable<R>)|null|undefined)} callback The
  1259. * fulfillment callback.
  1260. * @param {(function(*): (R|IThenable<R>)|null|undefined)} errback The
  1261. * rejection callback.
  1262. * @template R
  1263. * @private
  1264. */
  1265. invokeCallback_(callback, errback) {
  1266. var callbackFn = callback;
  1267. if (this.state_ === PromiseState.REJECTED) {
  1268. callbackFn = errback;
  1269. }
  1270. if (typeof callbackFn === 'function') {
  1271. if (isGenerator(callbackFn)) {
  1272. return consume(callbackFn, null, this.value_);
  1273. }
  1274. return callbackFn(this.value_);
  1275. } else if (this.state_ === PromiseState.REJECTED) {
  1276. throw this.value_;
  1277. } else {
  1278. return this.value_;
  1279. }
  1280. }
  1281. }
  1282. CancellableThenable.addImplementation(ManagedPromise);
  1283. /**
  1284. * @param {!ManagedPromise} promise
  1285. * @return {boolean}
  1286. */
  1287. function isPending(promise) {
  1288. return promise.state_ === PromiseState.PENDING;
  1289. }
  1290. /**
  1291. * Structural interface for a deferred promise resolver.
  1292. * @record
  1293. * @template T
  1294. */
  1295. function Resolver() {}
  1296. /**
  1297. * The promised value for this resolver.
  1298. * @type {!Thenable<T>}
  1299. */
  1300. Resolver.prototype.promise;
  1301. /**
  1302. * Resolves the promised value with the given `value`.
  1303. * @param {T|Thenable<T>} value
  1304. * @return {void}
  1305. */
  1306. Resolver.prototype.resolve;
  1307. /**
  1308. * Rejects the promised value with the given `reason`.
  1309. * @param {*} reason
  1310. * @return {void}
  1311. */
  1312. Resolver.prototype.reject;
  1313. /**
  1314. * Represents a value that will be resolved at some point in the future. This
  1315. * class represents the protected "producer" half of a ManagedPromise - each Deferred
  1316. * has a {@code promise} property that may be returned to consumers for
  1317. * registering callbacks, reserving the ability to resolve the deferred to the
  1318. * producer.
  1319. *
  1320. * If this Deferred is rejected and there are no listeners registered before
  1321. * the next turn of the event loop, the rejection will be passed to the
  1322. * {@link ControlFlow} as an unhandled failure.
  1323. *
  1324. * @template T
  1325. * @implements {Resolver<T>}
  1326. */
  1327. class Deferred {
  1328. /**
  1329. * @param {ControlFlow=} opt_flow The control flow this instance was
  1330. * created under. This should only be provided during unit tests.
  1331. * @param {?=} opt_skipLog An internal parameter used to skip logging the
  1332. * creation of this promise. This parameter has no effect unless it is
  1333. * strictly equal to an internal symbol. In other words, this parameter
  1334. * is always ignored for external code.
  1335. */
  1336. constructor(opt_flow, opt_skipLog) {
  1337. var fulfill, reject;
  1338. /** @type {!ManagedPromise<T>} */
  1339. this.promise = new ManagedPromise(function(f, r) {
  1340. fulfill = f;
  1341. reject = r;
  1342. }, opt_flow, opt_skipLog);
  1343. var self = this;
  1344. var checkNotSelf = function(value) {
  1345. if (value === self) {
  1346. throw new TypeError('May not resolve a Deferred with itself');
  1347. }
  1348. };
  1349. /**
  1350. * Resolves this deferred with the given value. It is safe to call this as a
  1351. * normal function (with no bound "this").
  1352. * @param {(T|IThenable<T>|Thenable)=} opt_value The fulfilled value.
  1353. * @const
  1354. */
  1355. this.resolve = function(opt_value) {
  1356. checkNotSelf(opt_value);
  1357. fulfill(opt_value);
  1358. };
  1359. /**
  1360. * An alias for {@link #resolve}.
  1361. * @const
  1362. */
  1363. this.fulfill = this.resolve;
  1364. /**
  1365. * Rejects this promise with the given reason. It is safe to call this as a
  1366. * normal function (with no bound "this").
  1367. * @param {*=} opt_reason The rejection reason.
  1368. * @const
  1369. */
  1370. this.reject = function(opt_reason) {
  1371. checkNotSelf(opt_reason);
  1372. reject(opt_reason);
  1373. };
  1374. }
  1375. }
  1376. /**
  1377. * Tests if a value is an Error-like object. This is more than an straight
  1378. * instanceof check since the value may originate from another context.
  1379. * @param {*} value The value to test.
  1380. * @return {boolean} Whether the value is an error.
  1381. */
  1382. function isError(value) {
  1383. return value instanceof Error ||
  1384. (!!value && typeof value === 'object'
  1385. && typeof value.message === 'string');
  1386. }
  1387. /**
  1388. * Determines whether a {@code value} should be treated as a promise.
  1389. * Any object whose "then" property is a function will be considered a promise.
  1390. *
  1391. * @param {?} value The value to test.
  1392. * @return {boolean} Whether the value is a promise.
  1393. */
  1394. function isPromise(value) {
  1395. try {
  1396. // Use array notation so the Closure compiler does not obfuscate away our
  1397. // contract.
  1398. return value
  1399. && (typeof value === 'object' || typeof value === 'function')
  1400. && typeof value['then'] === 'function';
  1401. } catch (ex) {
  1402. return false;
  1403. }
  1404. }
  1405. /**
  1406. * Creates a promise that will be resolved at a set time in the future.
  1407. * @param {number} ms The amount of time, in milliseconds, to wait before
  1408. * resolving the promise.
  1409. * @return {!Thenable} The promise.
  1410. */
  1411. function delayed(ms) {
  1412. return createPromise(resolve => {
  1413. setTimeout(() => resolve(), ms);
  1414. });
  1415. }
  1416. /**
  1417. * Creates a new deferred resolver.
  1418. *
  1419. * If the promise manager is currently enabled, this function will return a
  1420. * {@link Deferred} instance. Otherwise, it will return a resolver for a
  1421. * {@linkplain NativePromise native promise}.
  1422. *
  1423. * @return {!Resolver<T>} A new deferred resolver.
  1424. * @template T
  1425. */
  1426. function defer() {
  1427. if (usePromiseManager()) {
  1428. return new Deferred();
  1429. }
  1430. let resolve, reject;
  1431. let promise = new NativePromise((_resolve, _reject) => {
  1432. resolve = _resolve;
  1433. reject = _reject;
  1434. });
  1435. return {promise, resolve, reject};
  1436. }
  1437. /**
  1438. * Creates a promise that has been resolved with the given value.
  1439. *
  1440. * If the promise manager is currently enabled, this function will return a
  1441. * {@linkplain ManagedPromise managed promise}. Otherwise, it will return a
  1442. * {@linkplain NativePromise native promise}.
  1443. *
  1444. * @param {T=} opt_value The resolved value.
  1445. * @return {!Thenable<T>} The resolved promise.
  1446. * @template T
  1447. */
  1448. function fulfilled(opt_value) {
  1449. let ctor = usePromiseManager() ? ManagedPromise : NativePromise;
  1450. if (opt_value instanceof ctor) {
  1451. return /** @type {!Thenable} */(opt_value);
  1452. }
  1453. if (usePromiseManager()) {
  1454. // We can skip logging warnings about creating a managed promise because
  1455. // this function will automatically switch to use a native promise when
  1456. // the promise manager is disabled.
  1457. return new ManagedPromise(
  1458. resolve => resolve(opt_value), undefined, SKIP_LOG);
  1459. }
  1460. return NativePromise.resolve(opt_value);
  1461. }
  1462. /**
  1463. * Creates a promise that has been rejected with the given reason.
  1464. *
  1465. * If the promise manager is currently enabled, this function will return a
  1466. * {@linkplain ManagedPromise managed promise}. Otherwise, it will return a
  1467. * {@linkplain NativePromise native promise}.
  1468. *
  1469. * @param {*=} opt_reason The rejection reason; may be any value, but is
  1470. * usually an Error or a string.
  1471. * @return {!Thenable<?>} The rejected promise.
  1472. */
  1473. function rejected(opt_reason) {
  1474. if (usePromiseManager()) {
  1475. // We can skip logging warnings about creating a managed promise because
  1476. // this function will automatically switch to use a native promise when
  1477. // the promise manager is disabled.
  1478. return new ManagedPromise(
  1479. (_, reject) => reject(opt_reason), undefined, SKIP_LOG);
  1480. }
  1481. return NativePromise.reject(opt_reason);
  1482. }
  1483. /**
  1484. * Wraps a function that expects a node-style callback as its final
  1485. * argument. This callback expects two arguments: an error value (which will be
  1486. * null if the call succeeded), and the success value as the second argument.
  1487. * The callback will the resolve or reject the returned promise, based on its
  1488. * arguments.
  1489. * @param {!Function} fn The function to wrap.
  1490. * @param {...?} var_args The arguments to apply to the function, excluding the
  1491. * final callback.
  1492. * @return {!Thenable} A promise that will be resolved with the
  1493. * result of the provided function's callback.
  1494. */
  1495. function checkedNodeCall(fn, var_args) {
  1496. let args = Array.prototype.slice.call(arguments, 1);
  1497. return createPromise(function(fulfill, reject) {
  1498. try {
  1499. args.push(function(error, value) {
  1500. error ? reject(error) : fulfill(value);
  1501. });
  1502. fn.apply(undefined, args);
  1503. } catch (ex) {
  1504. reject(ex);
  1505. }
  1506. });
  1507. }
  1508. /**
  1509. * Registers a listener to invoke when a promise is resolved, regardless
  1510. * of whether the promise's value was successfully computed. This function
  1511. * is synonymous with the {@code finally} clause in a synchronous API:
  1512. *
  1513. * // Synchronous API:
  1514. * try {
  1515. * doSynchronousWork();
  1516. * } finally {
  1517. * cleanUp();
  1518. * }
  1519. *
  1520. * // Asynchronous promise API:
  1521. * doAsynchronousWork().finally(cleanUp);
  1522. *
  1523. * __Note:__ similar to the {@code finally} clause, if the registered
  1524. * callback returns a rejected promise or throws an error, it will silently
  1525. * replace the rejection error (if any) from this promise:
  1526. *
  1527. * try {
  1528. * throw Error('one');
  1529. * } finally {
  1530. * throw Error('two'); // Hides Error: one
  1531. * }
  1532. *
  1533. * let p = Promise.reject(Error('one'));
  1534. * promise.finally(p, function() {
  1535. * throw Error('two'); // Hides Error: one
  1536. * });
  1537. *
  1538. * @param {!IThenable<?>} promise The promise to add the listener to.
  1539. * @param {function(): (R|IThenable<R>)} callback The function to call when
  1540. * the promise is resolved.
  1541. * @return {!IThenable<R>} A promise that will be resolved with the callback
  1542. * result.
  1543. * @template R
  1544. */
  1545. function thenFinally(promise, callback) {
  1546. let error;
  1547. let mustThrow = false;
  1548. return promise.then(function() {
  1549. return callback();
  1550. }, function(err) {
  1551. error = err;
  1552. mustThrow = true;
  1553. return callback();
  1554. }).then(function() {
  1555. if (mustThrow) {
  1556. throw error;
  1557. }
  1558. });
  1559. }
  1560. /**
  1561. * Registers an observer on a promised {@code value}, returning a new promise
  1562. * that will be resolved when the value is. If {@code value} is not a promise,
  1563. * then the return promise will be immediately resolved.
  1564. * @param {*} value The value to observe.
  1565. * @param {Function=} opt_callback The function to call when the value is
  1566. * resolved successfully.
  1567. * @param {Function=} opt_errback The function to call when the value is
  1568. * rejected.
  1569. * @return {!Thenable} A new promise.
  1570. * @deprecated Use `promise.fulfilled(value).then(opt_callback, opt_errback)`
  1571. */
  1572. function when(value, opt_callback, opt_errback) {
  1573. return fulfilled(value).then(opt_callback, opt_errback);
  1574. }
  1575. /**
  1576. * Invokes the appropriate callback function as soon as a promised `value` is
  1577. * resolved.
  1578. *
  1579. * @param {*} value The value to observe.
  1580. * @param {Function} callback The function to call when the value is
  1581. * resolved successfully.
  1582. * @param {Function=} opt_errback The function to call when the value is
  1583. * rejected.
  1584. */
  1585. function asap(value, callback, opt_errback) {
  1586. if (isPromise(value)) {
  1587. value.then(callback, opt_errback);
  1588. } else if (callback) {
  1589. callback(value);
  1590. }
  1591. }
  1592. /**
  1593. * Given an array of promises, will return a promise that will be fulfilled
  1594. * with the fulfillment values of the input array's values. If any of the
  1595. * input array's promises are rejected, the returned promise will be rejected
  1596. * with the same reason.
  1597. *
  1598. * @param {!Array<(T|!ManagedPromise<T>)>} arr An array of
  1599. * promises to wait on.
  1600. * @return {!Thenable<!Array<T>>} A promise that is
  1601. * fulfilled with an array containing the fulfilled values of the
  1602. * input array, or rejected with the same reason as the first
  1603. * rejected value.
  1604. * @template T
  1605. */
  1606. function all(arr) {
  1607. return createPromise(function(fulfill, reject) {
  1608. var n = arr.length;
  1609. var values = [];
  1610. if (!n) {
  1611. fulfill(values);
  1612. return;
  1613. }
  1614. var toFulfill = n;
  1615. var onFulfilled = function(index, value) {
  1616. values[index] = value;
  1617. toFulfill--;
  1618. if (toFulfill == 0) {
  1619. fulfill(values);
  1620. }
  1621. };
  1622. function processPromise(index) {
  1623. asap(arr[index], function(value) {
  1624. onFulfilled(index, value);
  1625. }, reject);
  1626. }
  1627. for (var i = 0; i < n; ++i) {
  1628. processPromise(i);
  1629. }
  1630. });
  1631. }
  1632. /**
  1633. * Calls a function for each element in an array and inserts the result into a
  1634. * new array, which is used as the fulfillment value of the promise returned
  1635. * by this function.
  1636. *
  1637. * If the return value of the mapping function is a promise, this function
  1638. * will wait for it to be fulfilled before inserting it into the new array.
  1639. *
  1640. * If the mapping function throws or returns a rejected promise, the
  1641. * promise returned by this function will be rejected with the same reason.
  1642. * Only the first failure will be reported; all subsequent errors will be
  1643. * silently ignored.
  1644. *
  1645. * @param {!(Array<TYPE>|ManagedPromise<!Array<TYPE>>)} arr The
  1646. * array to iterator over, or a promise that will resolve to said array.
  1647. * @param {function(this: SELF, TYPE, number, !Array<TYPE>): ?} fn The
  1648. * function to call for each element in the array. This function should
  1649. * expect three arguments (the element, the index, and the array itself.
  1650. * @param {SELF=} opt_self The object to be used as the value of 'this' within
  1651. * {@code fn}.
  1652. * @template TYPE, SELF
  1653. */
  1654. function map(arr, fn, opt_self) {
  1655. return createPromise(resolve => resolve(arr)).then(v => {
  1656. if (!Array.isArray(v)) {
  1657. throw TypeError('not an array');
  1658. }
  1659. var arr = /** @type {!Array} */(v);
  1660. return createPromise(function(fulfill, reject) {
  1661. var n = arr.length;
  1662. var values = new Array(n);
  1663. (function processNext(i) {
  1664. for (; i < n; i++) {
  1665. if (i in arr) {
  1666. break;
  1667. }
  1668. }
  1669. if (i >= n) {
  1670. fulfill(values);
  1671. return;
  1672. }
  1673. try {
  1674. asap(
  1675. fn.call(opt_self, arr[i], i, /** @type {!Array} */(arr)),
  1676. function(value) {
  1677. values[i] = value;
  1678. processNext(i + 1);
  1679. },
  1680. reject);
  1681. } catch (ex) {
  1682. reject(ex);
  1683. }
  1684. })(0);
  1685. });
  1686. });
  1687. }
  1688. /**
  1689. * Calls a function for each element in an array, and if the function returns
  1690. * true adds the element to a new array.
  1691. *
  1692. * If the return value of the filter function is a promise, this function
  1693. * will wait for it to be fulfilled before determining whether to insert the
  1694. * element into the new array.
  1695. *
  1696. * If the filter function throws or returns a rejected promise, the promise
  1697. * returned by this function will be rejected with the same reason. Only the
  1698. * first failure will be reported; all subsequent errors will be silently
  1699. * ignored.
  1700. *
  1701. * @param {!(Array<TYPE>|ManagedPromise<!Array<TYPE>>)} arr The
  1702. * array to iterator over, or a promise that will resolve to said array.
  1703. * @param {function(this: SELF, TYPE, number, !Array<TYPE>): (
  1704. * boolean|ManagedPromise<boolean>)} fn The function
  1705. * to call for each element in the array.
  1706. * @param {SELF=} opt_self The object to be used as the value of 'this' within
  1707. * {@code fn}.
  1708. * @template TYPE, SELF
  1709. */
  1710. function filter(arr, fn, opt_self) {
  1711. return createPromise(resolve => resolve(arr)).then(v => {
  1712. if (!Array.isArray(v)) {
  1713. throw TypeError('not an array');
  1714. }
  1715. var arr = /** @type {!Array} */(v);
  1716. return createPromise(function(fulfill, reject) {
  1717. var n = arr.length;
  1718. var values = [];
  1719. var valuesLength = 0;
  1720. (function processNext(i) {
  1721. for (; i < n; i++) {
  1722. if (i in arr) {
  1723. break;
  1724. }
  1725. }
  1726. if (i >= n) {
  1727. fulfill(values);
  1728. return;
  1729. }
  1730. try {
  1731. var value = arr[i];
  1732. var include = fn.call(opt_self, value, i, /** @type {!Array} */(arr));
  1733. asap(include, function(include) {
  1734. if (include) {
  1735. values[valuesLength++] = value;
  1736. }
  1737. processNext(i + 1);
  1738. }, reject);
  1739. } catch (ex) {
  1740. reject(ex);
  1741. }
  1742. })(0);
  1743. });
  1744. });
  1745. }
  1746. /**
  1747. * Returns a promise that will be resolved with the input value in a
  1748. * fully-resolved state. If the value is an array, each element will be fully
  1749. * resolved. Likewise, if the value is an object, all keys will be fully
  1750. * resolved. In both cases, all nested arrays and objects will also be
  1751. * fully resolved. All fields are resolved in place; the returned promise will
  1752. * resolve on {@code value} and not a copy.
  1753. *
  1754. * Warning: This function makes no checks against objects that contain
  1755. * cyclical references:
  1756. *
  1757. * var value = {};
  1758. * value['self'] = value;
  1759. * promise.fullyResolved(value); // Stack overflow.
  1760. *
  1761. * @param {*} value The value to fully resolve.
  1762. * @return {!Thenable} A promise for a fully resolved version
  1763. * of the input value.
  1764. */
  1765. function fullyResolved(value) {
  1766. if (isPromise(value)) {
  1767. return fulfilled(value).then(fullyResolveValue);
  1768. }
  1769. return fullyResolveValue(value);
  1770. }
  1771. /**
  1772. * @param {*} value The value to fully resolve. If a promise, assumed to
  1773. * already be resolved.
  1774. * @return {!Thenable} A promise for a fully resolved version
  1775. * of the input value.
  1776. */
  1777. function fullyResolveValue(value) {
  1778. if (Array.isArray(value)) {
  1779. return fullyResolveKeys(/** @type {!Array} */ (value));
  1780. }
  1781. if (isPromise(value)) {
  1782. if (isPromise(value)) {
  1783. // We get here when the original input value is a promise that
  1784. // resolves to itself. When the user provides us with such a promise,
  1785. // trust that it counts as a "fully resolved" value and return it.
  1786. // Of course, since it's already a promise, we can just return it
  1787. // to the user instead of wrapping it in another promise.
  1788. return /** @type {!ManagedPromise} */ (value);
  1789. }
  1790. }
  1791. if (value && typeof value === 'object') {
  1792. return fullyResolveKeys(/** @type {!Object} */ (value));
  1793. }
  1794. if (typeof value === 'function') {
  1795. return fullyResolveKeys(/** @type {!Object} */ (value));
  1796. }
  1797. return createPromise(resolve => resolve(value));
  1798. }
  1799. /**
  1800. * @param {!(Array|Object)} obj the object to resolve.
  1801. * @return {!Thenable} A promise that will be resolved with the
  1802. * input object once all of its values have been fully resolved.
  1803. */
  1804. function fullyResolveKeys(obj) {
  1805. var isArray = Array.isArray(obj);
  1806. var numKeys = isArray ? obj.length : (function() {
  1807. let n = 0;
  1808. for (let key in obj) {
  1809. n += 1;
  1810. }
  1811. return n;
  1812. })();
  1813. if (!numKeys) {
  1814. return createPromise(resolve => resolve(obj));
  1815. }
  1816. function forEachProperty(obj, fn) {
  1817. for (let key in obj) {
  1818. fn.call(null, obj[key], key, obj);
  1819. }
  1820. }
  1821. function forEachElement(arr, fn) {
  1822. arr.forEach(fn);
  1823. }
  1824. var numResolved = 0;
  1825. return createPromise(function(fulfill, reject) {
  1826. var forEachKey = isArray ? forEachElement: forEachProperty;
  1827. forEachKey(obj, function(partialValue, key) {
  1828. if (!Array.isArray(partialValue)
  1829. && (!partialValue || typeof partialValue !== 'object')) {
  1830. maybeResolveValue();
  1831. return;
  1832. }
  1833. fullyResolved(partialValue).then(
  1834. function(resolvedValue) {
  1835. obj[key] = resolvedValue;
  1836. maybeResolveValue();
  1837. },
  1838. reject);
  1839. });
  1840. function maybeResolveValue() {
  1841. if (++numResolved == numKeys) {
  1842. fulfill(obj);
  1843. }
  1844. }
  1845. });
  1846. }
  1847. //////////////////////////////////////////////////////////////////////////////
  1848. //
  1849. // ControlFlow
  1850. //
  1851. //////////////////////////////////////////////////////////////////////////////
  1852. /**
  1853. * Defines methods for coordinating the execution of asynchronous tasks.
  1854. * @record
  1855. */
  1856. class Scheduler {
  1857. /**
  1858. * Schedules a task for execution. If the task function is a generator, the
  1859. * task will be executed using {@link ./promise.consume consume()}.
  1860. *
  1861. * @param {function(): (T|IThenable<T>)} fn The function to call to start the
  1862. * task.
  1863. * @param {string=} opt_description A description of the task for debugging
  1864. * purposes.
  1865. * @return {!Thenable<T>} A promise that will be resolved with the task
  1866. * result.
  1867. * @template T
  1868. */
  1869. execute(fn, opt_description) {}
  1870. /**
  1871. * Creates a new promise using the given resolver function.
  1872. *
  1873. * @param {function(
  1874. * function((T|IThenable<T>|Thenable|null)=),
  1875. * function(*=))} resolver
  1876. * @return {!Thenable<T>}
  1877. * @template T
  1878. */
  1879. promise(resolver) {}
  1880. /**
  1881. * Schedules a `setTimeout` call.
  1882. *
  1883. * @param {number} ms The timeout delay, in milliseconds.
  1884. * @param {string=} opt_description A description to accompany the timeout.
  1885. * @return {!Thenable<void>} A promise that will be resolved when the timeout
  1886. * fires.
  1887. */
  1888. timeout(ms, opt_description) {}
  1889. /**
  1890. * Schedules a task to wait for a condition to hold.
  1891. *
  1892. * If the condition is defined as a function, it may return any value. Promise
  1893. * will be resolved before testing if the condition holds (resolution time
  1894. * counts towards the timeout). Once resolved, values are always evaluated as
  1895. * booleans.
  1896. *
  1897. * If the condition function throws, or returns a rejected promise, the
  1898. * wait task will fail.
  1899. *
  1900. * If the condition is defined as a promise, the scheduler will wait for it to
  1901. * settle. If the timeout expires before the promise settles, the promise
  1902. * returned by this function will be rejected.
  1903. *
  1904. * If this function is invoked with `timeout === 0`, or the timeout is
  1905. * omitted, this scheduler will wait indefinitely for the condition to be
  1906. * satisfied.
  1907. *
  1908. * @param {(!IThenable<T>|function())} condition The condition to poll,
  1909. * or a promise to wait on.
  1910. * @param {number=} opt_timeout How long to wait, in milliseconds, for the
  1911. * condition to hold before timing out. If omitted, the flow will wait
  1912. * indefinitely.
  1913. * @param {string=} opt_message An optional error message to include if the
  1914. * wait times out; defaults to the empty string.
  1915. * @return {!Thenable<T>} A promise that will be fulfilled
  1916. * when the condition has been satisfied. The promise shall be rejected
  1917. * if the wait times out waiting for the condition.
  1918. * @throws {TypeError} If condition is not a function or promise or if timeout
  1919. * is not a number >= 0.
  1920. * @template T
  1921. */
  1922. wait(condition, opt_timeout, opt_message) {}
  1923. }
  1924. let USE_PROMISE_MANAGER;
  1925. function usePromiseManager() {
  1926. if (typeof USE_PROMISE_MANAGER !== 'undefined') {
  1927. return !!USE_PROMISE_MANAGER;
  1928. }
  1929. return process.env['SELENIUM_PROMISE_MANAGER'] === undefined
  1930. || !/^0|false$/i.test(process.env['SELENIUM_PROMISE_MANAGER']);
  1931. }
  1932. /**
  1933. * Creates a new promise with the given `resolver` function. If the promise
  1934. * manager is currently enabled, the returned promise will be a
  1935. * {@linkplain ManagedPromise} instance. Otherwise, it will be a native promise.
  1936. *
  1937. * @param {function(
  1938. * function((T|IThenable<T>|Thenable|null)=),
  1939. * function(*=))} resolver
  1940. * @return {!Thenable<T>}
  1941. * @template T
  1942. */
  1943. function createPromise(resolver) {
  1944. let ctor = usePromiseManager() ? ManagedPromise : NativePromise;
  1945. return new ctor(resolver);
  1946. }
  1947. /**
  1948. * @param {!Scheduler} scheduler The scheduler to use.
  1949. * @param {(!IThenable<T>|function())} condition The condition to poll,
  1950. * or a promise to wait on.
  1951. * @param {number=} opt_timeout How long to wait, in milliseconds, for the
  1952. * condition to hold before timing out. If omitted, the flow will wait
  1953. * indefinitely.
  1954. * @param {string=} opt_message An optional error message to include if the
  1955. * wait times out; defaults to the empty string.
  1956. * @return {!Thenable<T>} A promise that will be fulfilled
  1957. * when the condition has been satisfied. The promise shall be rejected
  1958. * if the wait times out waiting for the condition.
  1959. * @throws {TypeError} If condition is not a function or promise or if timeout
  1960. * is not a number >= 0.
  1961. * @template T
  1962. */
  1963. function scheduleWait(scheduler, condition, opt_timeout, opt_message) {
  1964. let timeout = opt_timeout || 0;
  1965. if (typeof timeout !== 'number' || timeout < 0) {
  1966. throw TypeError('timeout must be a number >= 0: ' + timeout);
  1967. }
  1968. if (isPromise(condition)) {
  1969. return scheduler.execute(function() {
  1970. if (!timeout) {
  1971. return condition;
  1972. }
  1973. return scheduler.promise(function(fulfill, reject) {
  1974. let start = Date.now();
  1975. let timer = setTimeout(function() {
  1976. timer = null;
  1977. reject(
  1978. new error.TimeoutError(
  1979. (opt_message ? opt_message + '\n' : '')
  1980. + 'Timed out waiting for promise to resolve after '
  1981. + (Date.now() - start) + 'ms'));
  1982. }, timeout);
  1983. /** @type {Thenable} */(condition).then(
  1984. function(value) {
  1985. timer && clearTimeout(timer);
  1986. fulfill(value);
  1987. },
  1988. function(error) {
  1989. timer && clearTimeout(timer);
  1990. reject(error);
  1991. });
  1992. });
  1993. }, opt_message || '<anonymous wait: promise resolution>');
  1994. }
  1995. if (typeof condition !== 'function') {
  1996. throw TypeError('Invalid condition; must be a function or promise: ' +
  1997. typeof condition);
  1998. }
  1999. if (isGenerator(condition)) {
  2000. let original = condition;
  2001. condition = () => consume(original);
  2002. }
  2003. return scheduler.execute(function() {
  2004. var startTime = Date.now();
  2005. return scheduler.promise(function(fulfill, reject) {
  2006. pollCondition();
  2007. function pollCondition() {
  2008. var conditionFn = /** @type {function()} */(condition);
  2009. scheduler.execute(conditionFn).then(function(value) {
  2010. var elapsed = Date.now() - startTime;
  2011. if (!!value) {
  2012. fulfill(value);
  2013. } else if (timeout && elapsed >= timeout) {
  2014. reject(
  2015. new error.TimeoutError(
  2016. (opt_message ? opt_message + '\n' : '')
  2017. + `Wait timed out after ${elapsed}ms`));
  2018. } else {
  2019. // Do not use asyncRun here because we need a non-micro yield
  2020. // here so the UI thread is given a chance when running in a
  2021. // browser.
  2022. setTimeout(pollCondition, 0);
  2023. }
  2024. }, reject);
  2025. }
  2026. });
  2027. }, opt_message || '<anonymous wait>');
  2028. }
  2029. /**
  2030. * A scheduler that executes all tasks immediately, with no coordination. This
  2031. * class is an event emitter for API compatibility with the {@link ControlFlow},
  2032. * however, it emits no events.
  2033. *
  2034. * @implements {Scheduler}
  2035. */
  2036. class SimpleScheduler extends events.EventEmitter {
  2037. /** @override */
  2038. execute(fn) {
  2039. return this.promise((resolve, reject) => {
  2040. try {
  2041. if (isGenerator(fn)) {
  2042. consume(fn).then(resolve, reject);
  2043. } else {
  2044. resolve(fn.call(undefined));
  2045. }
  2046. } catch (ex) {
  2047. reject(ex);
  2048. }
  2049. });
  2050. }
  2051. /** @override */
  2052. promise(resolver) {
  2053. return new NativePromise(resolver);
  2054. }
  2055. /** @override */
  2056. timeout(ms) {
  2057. return this.promise(resolve => setTimeout(_ => resolve(), ms));
  2058. }
  2059. /** @override */
  2060. wait(condition, opt_timeout, opt_message) {
  2061. return scheduleWait(this, condition, opt_timeout, opt_message);
  2062. }
  2063. }
  2064. const SIMPLE_SCHEDULER = new SimpleScheduler;
  2065. /**
  2066. * Handles the execution of scheduled tasks, each of which may be an
  2067. * asynchronous operation. The control flow will ensure tasks are executed in
  2068. * the order scheduled, starting each task only once those before it have
  2069. * completed.
  2070. *
  2071. * Each task scheduled within this flow may return a {@link ManagedPromise} to
  2072. * indicate it is an asynchronous operation. The ControlFlow will wait for such
  2073. * promises to be resolved before marking the task as completed.
  2074. *
  2075. * Tasks and each callback registered on a {@link ManagedPromise} will be run
  2076. * in their own ControlFlow frame. Any tasks scheduled within a frame will take
  2077. * priority over previously scheduled tasks. Furthermore, if any of the tasks in
  2078. * the frame fail, the remainder of the tasks in that frame will be discarded
  2079. * and the failure will be propagated to the user through the callback/task's
  2080. * promised result.
  2081. *
  2082. * Each time a ControlFlow empties its task queue, it will fire an
  2083. * {@link ControlFlow.EventType.IDLE IDLE} event. Conversely, whenever
  2084. * the flow terminates due to an unhandled error, it will remove all
  2085. * remaining tasks in its queue and fire an
  2086. * {@link ControlFlow.EventType.UNCAUGHT_EXCEPTION UNCAUGHT_EXCEPTION} event.
  2087. * If there are no listeners registered with the flow, the error will be
  2088. * rethrown to the global error handler.
  2089. *
  2090. * Refer to the {@link ./promise} module documentation for a detailed
  2091. * explanation of how the ControlFlow coordinates task execution.
  2092. *
  2093. * @implements {Scheduler}
  2094. * @final
  2095. */
  2096. class ControlFlow extends events.EventEmitter {
  2097. constructor() {
  2098. if (!usePromiseManager()) {
  2099. throw TypeError(
  2100. 'Cannot instantiate control flow when the promise manager has'
  2101. + ' been disabled');
  2102. }
  2103. super();
  2104. /** @private {boolean} */
  2105. this.propagateUnhandledRejections_ = true;
  2106. /** @private {TaskQueue} */
  2107. this.activeQueue_ = null;
  2108. /** @private {Set<TaskQueue>} */
  2109. this.taskQueues_ = null;
  2110. /**
  2111. * Microtask that controls shutting down the control flow. Upon shut down,
  2112. * the flow will emit an
  2113. * {@link ControlFlow.EventType.IDLE} event. Idle events
  2114. * always follow a brief timeout in order to catch latent errors from the
  2115. * last completed task. If this task had a callback registered, but no
  2116. * errback, and the task fails, the unhandled failure would not be reported
  2117. * by the promise system until the next turn of the event loop:
  2118. *
  2119. * // Schedule 1 task that fails.
  2120. * var result = promise.controlFlow().execute(
  2121. * () => promise.rejected('failed'), 'example');
  2122. * // Set a callback on the result. This delays reporting the unhandled
  2123. * // failure for 1 turn of the event loop.
  2124. * result.then(function() {});
  2125. *
  2126. * @private {MicroTask}
  2127. */
  2128. this.shutdownTask_ = null;
  2129. /**
  2130. * ID for a long running interval used to keep a Node.js process running
  2131. * while a control flow's event loop is still working. This is a cheap hack
  2132. * required since JS events are only scheduled to run when there is
  2133. * _actually_ something to run. When a control flow is waiting on a task,
  2134. * there will be nothing in the JS event loop and the process would
  2135. * terminate without this.
  2136. * @private
  2137. */
  2138. this.hold_ = null;
  2139. }
  2140. /**
  2141. * Returns a string representation of this control flow, which is its current
  2142. * {@linkplain #getSchedule() schedule}, sans task stack traces.
  2143. * @return {string} The string representation of this control flow.
  2144. * @override
  2145. */
  2146. toString() {
  2147. return this.getSchedule();
  2148. }
  2149. /**
  2150. * Sets whether any unhandled rejections should propagate up through the
  2151. * control flow stack and cause rejections within parent tasks. If error
  2152. * propagation is disabled, tasks will not be aborted when an unhandled
  2153. * promise rejection is detected, but the rejection _will_ trigger an
  2154. * {@link ControlFlow.EventType.UNCAUGHT_EXCEPTION} event.
  2155. *
  2156. * The default behavior is to propagate all unhandled rejections. _The use
  2157. * of this option is highly discouraged._
  2158. *
  2159. * @param {boolean} propagate whether to propagate errors.
  2160. */
  2161. setPropagateUnhandledRejections(propagate) {
  2162. this.propagateUnhandledRejections_ = propagate;
  2163. }
  2164. /**
  2165. * @return {boolean} Whether this flow is currently idle.
  2166. */
  2167. isIdle() {
  2168. return !this.shutdownTask_ && (!this.taskQueues_ || !this.taskQueues_.size);
  2169. }
  2170. /**
  2171. * Resets this instance, clearing its queue and removing all event listeners.
  2172. */
  2173. reset() {
  2174. this.cancelQueues_(new FlowResetError);
  2175. this.emit(ControlFlow.EventType.RESET);
  2176. this.removeAllListeners();
  2177. this.cancelShutdown_();
  2178. }
  2179. /**
  2180. * Generates an annotated string describing the internal state of this control
  2181. * flow, including the currently executing as well as pending tasks. If
  2182. * {@code opt_includeStackTraces === true}, the string will include the
  2183. * stack trace from when each task was scheduled.
  2184. * @param {string=} opt_includeStackTraces Whether to include the stack traces
  2185. * from when each task was scheduled. Defaults to false.
  2186. * @return {string} String representation of this flow's internal state.
  2187. */
  2188. getSchedule(opt_includeStackTraces) {
  2189. var ret = 'ControlFlow::' + getUid(this);
  2190. var activeQueue = this.activeQueue_;
  2191. if (!this.taskQueues_ || !this.taskQueues_.size) {
  2192. return ret;
  2193. }
  2194. var childIndent = '| ';
  2195. for (var q of this.taskQueues_) {
  2196. ret += '\n' + printQ(q, childIndent);
  2197. }
  2198. return ret;
  2199. function printQ(q, indent) {
  2200. var ret = q.toString();
  2201. if (q === activeQueue) {
  2202. ret = '(active) ' + ret;
  2203. }
  2204. var prefix = indent + childIndent;
  2205. if (q.pending_) {
  2206. if (q.pending_.q.state_ !== TaskQueueState.FINISHED) {
  2207. ret += '\n' + prefix + '(pending) ' + q.pending_.task;
  2208. ret += '\n' + printQ(q.pending_.q, prefix + childIndent);
  2209. } else {
  2210. ret += '\n' + prefix + '(blocked) ' + q.pending_.task;
  2211. }
  2212. }
  2213. if (q.interrupts_) {
  2214. q.interrupts_.forEach((task) => {
  2215. ret += '\n' + prefix + task;
  2216. });
  2217. }
  2218. if (q.tasks_) {
  2219. q.tasks_.forEach((task) => ret += printTask(task, '\n' + prefix));
  2220. }
  2221. return indent + ret;
  2222. }
  2223. function printTask(task, prefix) {
  2224. var ret = prefix + task;
  2225. if (opt_includeStackTraces && task.promise.stack_) {
  2226. ret += prefix + childIndent
  2227. + (task.promise.stack_.stack || task.promise.stack_)
  2228. .replace(/\n/g, prefix);
  2229. }
  2230. return ret;
  2231. }
  2232. }
  2233. /**
  2234. * Returns the currently active task queue for this flow. If there is no
  2235. * active queue, one will be created.
  2236. * @return {!TaskQueue} the currently active task queue for this flow.
  2237. * @private
  2238. */
  2239. getActiveQueue_() {
  2240. if (this.activeQueue_) {
  2241. return this.activeQueue_;
  2242. }
  2243. this.activeQueue_ = new TaskQueue(this);
  2244. if (!this.taskQueues_) {
  2245. this.taskQueues_ = new Set();
  2246. }
  2247. this.taskQueues_.add(this.activeQueue_);
  2248. this.activeQueue_
  2249. .once('end', this.onQueueEnd_, this)
  2250. .once('error', this.onQueueError_, this);
  2251. asyncRun(() => this.activeQueue_ = null);
  2252. this.activeQueue_.start();
  2253. return this.activeQueue_;
  2254. }
  2255. /** @override */
  2256. execute(fn, opt_description) {
  2257. if (isGenerator(fn)) {
  2258. let original = fn;
  2259. fn = () => consume(original);
  2260. }
  2261. if (!this.hold_) {
  2262. let holdIntervalMs = 2147483647; // 2^31-1; max timer length for Node.js
  2263. this.hold_ = setInterval(function() {}, holdIntervalMs);
  2264. }
  2265. let task = new Task(
  2266. this, fn, opt_description || '<anonymous>',
  2267. {name: 'Task', top: ControlFlow.prototype.execute},
  2268. true);
  2269. let q = this.getActiveQueue_();
  2270. for (let i = q.tasks_.length; i > 0; i--) {
  2271. let previousTask = q.tasks_[i - 1];
  2272. if (previousTask.userTask_) {
  2273. FLOW_LOG.warning(() => {
  2274. return `Detected scheduling of an unchained task.
  2275. When the promise manager is disabled, unchained tasks will not wait for
  2276. previously scheduled tasks to finish before starting to execute.
  2277. New task: ${task.promise.stack_.stack}
  2278. Previous task: ${previousTask.promise.stack_.stack}`.split(/\n/).join('\n ');
  2279. });
  2280. break;
  2281. }
  2282. }
  2283. q.enqueue(task);
  2284. this.emit(ControlFlow.EventType.SCHEDULE_TASK, task.description);
  2285. return task.promise;
  2286. }
  2287. /** @override */
  2288. promise(resolver) {
  2289. return new ManagedPromise(resolver, this, SKIP_LOG);
  2290. }
  2291. /** @override */
  2292. timeout(ms, opt_description) {
  2293. return this.execute(() => {
  2294. return this.promise(resolve => setTimeout(() => resolve(), ms));
  2295. }, opt_description);
  2296. }
  2297. /** @override */
  2298. wait(condition, opt_timeout, opt_message) {
  2299. return scheduleWait(this, condition, opt_timeout, opt_message);
  2300. }
  2301. /**
  2302. * Executes a function in the next available turn of the JavaScript event
  2303. * loop. This ensures the function runs with its own task queue and any
  2304. * scheduled tasks will run in "parallel" to those scheduled in the current
  2305. * function.
  2306. *
  2307. * flow.execute(() => console.log('a'));
  2308. * flow.execute(() => console.log('b'));
  2309. * flow.execute(() => console.log('c'));
  2310. * flow.async(() => {
  2311. * flow.execute(() => console.log('d'));
  2312. * flow.execute(() => console.log('e'));
  2313. * });
  2314. * flow.async(() => {
  2315. * flow.execute(() => console.log('f'));
  2316. * flow.execute(() => console.log('g'));
  2317. * });
  2318. * flow.once('idle', () => console.log('fin'));
  2319. * // a
  2320. * // d
  2321. * // f
  2322. * // b
  2323. * // e
  2324. * // g
  2325. * // c
  2326. * // fin
  2327. *
  2328. * If the function itself throws, the error will be treated the same as an
  2329. * unhandled rejection within the control flow.
  2330. *
  2331. * __NOTE__: This function is considered _unstable_.
  2332. *
  2333. * @param {!Function} fn The function to execute.
  2334. * @param {Object=} opt_self The object in whose context to run the function.
  2335. * @param {...*} var_args Any arguments to pass to the function.
  2336. */
  2337. async(fn, opt_self, var_args) {
  2338. asyncRun(() => {
  2339. // Clear any lingering queues, forces getActiveQueue_ to create a new one.
  2340. this.activeQueue_ = null;
  2341. var q = this.getActiveQueue_();
  2342. try {
  2343. q.execute_(fn.bind(opt_self, var_args));
  2344. } catch (ex) {
  2345. var cancellationError = CancellationError.wrap(ex,
  2346. 'Function passed to ControlFlow.async() threw');
  2347. cancellationError.silent_ = true;
  2348. q.abort_(cancellationError);
  2349. } finally {
  2350. this.activeQueue_ = null;
  2351. }
  2352. });
  2353. }
  2354. /**
  2355. * Event handler for when a task queue is exhausted. This starts the shutdown
  2356. * sequence for this instance if there are no remaining task queues: after
  2357. * one turn of the event loop, this object will emit the
  2358. * {@link ControlFlow.EventType.IDLE IDLE} event to signal
  2359. * listeners that it has completed. During this wait, if another task is
  2360. * scheduled, the shutdown will be aborted.
  2361. *
  2362. * @param {!TaskQueue} q the completed task queue.
  2363. * @private
  2364. */
  2365. onQueueEnd_(q) {
  2366. if (!this.taskQueues_) {
  2367. return;
  2368. }
  2369. this.taskQueues_.delete(q);
  2370. vlog(1, () => q + ' has finished');
  2371. vlog(1, () => this.taskQueues_.size + ' queues remain\n' + this, this);
  2372. if (!this.taskQueues_.size) {
  2373. if (this.shutdownTask_) {
  2374. throw Error('Already have a shutdown task??');
  2375. }
  2376. vlog(1, () => 'Scheduling shutdown\n' + this);
  2377. this.shutdownTask_ = new MicroTask(() => this.shutdown_());
  2378. }
  2379. }
  2380. /**
  2381. * Event handler for when a task queue terminates with an error. This triggers
  2382. * the cancellation of all other task queues and a
  2383. * {@link ControlFlow.EventType.UNCAUGHT_EXCEPTION} event.
  2384. * If there are no error event listeners registered with this instance, the
  2385. * error will be rethrown to the global error handler.
  2386. *
  2387. * @param {*} error the error that caused the task queue to terminate.
  2388. * @param {!TaskQueue} q the task queue.
  2389. * @private
  2390. */
  2391. onQueueError_(error, q) {
  2392. if (this.taskQueues_) {
  2393. this.taskQueues_.delete(q);
  2394. }
  2395. this.cancelQueues_(CancellationError.wrap(
  2396. error, 'There was an uncaught error in the control flow'));
  2397. this.cancelShutdown_();
  2398. this.cancelHold_();
  2399. setTimeout(() => {
  2400. let listeners = this.listeners(ControlFlow.EventType.UNCAUGHT_EXCEPTION);
  2401. if (!listeners.size) {
  2402. throw error;
  2403. } else {
  2404. this.reportUncaughtException_(error);
  2405. }
  2406. }, 0);
  2407. }
  2408. /**
  2409. * Cancels all remaining task queues.
  2410. * @param {!CancellationError} reason The cancellation reason.
  2411. * @private
  2412. */
  2413. cancelQueues_(reason) {
  2414. reason.silent_ = true;
  2415. if (this.taskQueues_) {
  2416. for (var q of this.taskQueues_) {
  2417. q.removeAllListeners();
  2418. q.abort_(reason);
  2419. }
  2420. this.taskQueues_.clear();
  2421. this.taskQueues_ = null;
  2422. }
  2423. }
  2424. /**
  2425. * Reports an uncaught exception using a
  2426. * {@link ControlFlow.EventType.UNCAUGHT_EXCEPTION} event.
  2427. *
  2428. * @param {*} e the error to report.
  2429. * @private
  2430. */
  2431. reportUncaughtException_(e) {
  2432. this.emit(ControlFlow.EventType.UNCAUGHT_EXCEPTION, e);
  2433. }
  2434. /** @private */
  2435. cancelHold_() {
  2436. if (this.hold_) {
  2437. clearInterval(this.hold_);
  2438. this.hold_ = null;
  2439. }
  2440. }
  2441. /** @private */
  2442. shutdown_() {
  2443. vlog(1, () => 'Going idle: ' + this);
  2444. this.cancelHold_();
  2445. this.shutdownTask_ = null;
  2446. this.emit(ControlFlow.EventType.IDLE);
  2447. }
  2448. /**
  2449. * Cancels the shutdown sequence if it is currently scheduled.
  2450. * @private
  2451. */
  2452. cancelShutdown_() {
  2453. if (this.shutdownTask_) {
  2454. this.shutdownTask_.cancel();
  2455. this.shutdownTask_ = null;
  2456. }
  2457. }
  2458. }
  2459. /**
  2460. * Events that may be emitted by an {@link ControlFlow}.
  2461. * @enum {string}
  2462. */
  2463. ControlFlow.EventType = {
  2464. /** Emitted when all tasks have been successfully executed. */
  2465. IDLE: 'idle',
  2466. /** Emitted when a ControlFlow has been reset. */
  2467. RESET: 'reset',
  2468. /** Emitted whenever a new task has been scheduled. */
  2469. SCHEDULE_TASK: 'scheduleTask',
  2470. /**
  2471. * Emitted whenever a control flow aborts due to an unhandled promise
  2472. * rejection. This event will be emitted along with the offending rejection
  2473. * reason. Upon emitting this event, the control flow will empty its task
  2474. * queue and revert to its initial state.
  2475. */
  2476. UNCAUGHT_EXCEPTION: 'uncaughtException'
  2477. };
  2478. /**
  2479. * Wraps a function to execute as a cancellable micro task.
  2480. * @final
  2481. */
  2482. class MicroTask {
  2483. /**
  2484. * @param {function()} fn The function to run as a micro task.
  2485. */
  2486. constructor(fn) {
  2487. /** @private {boolean} */
  2488. this.cancelled_ = false;
  2489. asyncRun(() => {
  2490. if (!this.cancelled_) {
  2491. fn();
  2492. }
  2493. });
  2494. }
  2495. /**
  2496. * Runs the given function after a microtask yield.
  2497. * @param {function()} fn The function to run.
  2498. */
  2499. static run(fn) {
  2500. NativePromise.resolve().then(function() {
  2501. try {
  2502. fn();
  2503. } catch (ignored) {
  2504. // Do nothing.
  2505. }
  2506. });
  2507. }
  2508. /**
  2509. * Cancels the execution of this task. Note: this will not prevent the task
  2510. * timer from firing, just the invocation of the wrapped function.
  2511. */
  2512. cancel() {
  2513. this.cancelled_ = true;
  2514. }
  2515. }
  2516. /**
  2517. * A task to be executed by a {@link ControlFlow}.
  2518. *
  2519. * @template T
  2520. * @final
  2521. */
  2522. class Task extends Deferred {
  2523. /**
  2524. * @param {!ControlFlow} flow The flow this instances belongs
  2525. * to.
  2526. * @param {function(): (T|!ManagedPromise<T>)} fn The function to
  2527. * call when the task executes. If it returns a
  2528. * {@link ManagedPromise}, the flow will wait for it to be
  2529. * resolved before starting the next task.
  2530. * @param {string} description A description of the task for debugging.
  2531. * @param {{name: string, top: !Function}=} opt_stackOptions Options to use
  2532. * when capturing the stacktrace for when this task was created.
  2533. * @param {boolean=} opt_isUserTask Whether this task was explicitly scheduled
  2534. * by the use of the promise manager.
  2535. */
  2536. constructor(flow, fn, description, opt_stackOptions, opt_isUserTask) {
  2537. super(flow, SKIP_LOG);
  2538. getUid(this);
  2539. /** @type {function(): (T|!ManagedPromise<T>)} */
  2540. this.execute = fn;
  2541. /** @type {string} */
  2542. this.description = description;
  2543. /** @type {TaskQueue} */
  2544. this.queue = null;
  2545. /** @private @const {boolean} */
  2546. this.userTask_ = !!opt_isUserTask;
  2547. /**
  2548. * Whether this task is considered block. A blocked task may be registered
  2549. * in a task queue, but will be dropped if it is still blocked when it
  2550. * reaches the front of the queue. A dropped task may always be rescheduled.
  2551. *
  2552. * Blocked tasks are used when a callback is attached to an unsettled
  2553. * promise to reserve a spot in line (in a manner of speaking). If the
  2554. * promise is not settled before the callback reaches the front of the
  2555. * of the queue, it will be dropped. Once the promise is settled, the
  2556. * dropped task will be rescheduled as an interrupt on the currently task
  2557. * queue.
  2558. *
  2559. * @type {boolean}
  2560. */
  2561. this.blocked = false;
  2562. if (opt_stackOptions) {
  2563. this.promise.stack_ = captureStackTrace(
  2564. opt_stackOptions.name, this.description, opt_stackOptions.top);
  2565. }
  2566. }
  2567. /** @override */
  2568. toString() {
  2569. return 'Task::' + getUid(this) + '<' + this.description + '>';
  2570. }
  2571. }
  2572. /** @enum {string} */
  2573. const TaskQueueState = {
  2574. NEW: 'new',
  2575. STARTED: 'started',
  2576. FINISHED: 'finished'
  2577. };
  2578. /**
  2579. * @final
  2580. */
  2581. class TaskQueue extends events.EventEmitter {
  2582. /** @param {!ControlFlow} flow . */
  2583. constructor(flow) {
  2584. super();
  2585. /** @private {string} */
  2586. this.name_ = 'TaskQueue::' + getUid(this);
  2587. /** @private {!ControlFlow} */
  2588. this.flow_ = flow;
  2589. /** @private {!Array<!Task>} */
  2590. this.tasks_ = [];
  2591. /** @private {Array<!Task>} */
  2592. this.interrupts_ = null;
  2593. /** @private {({task: !Task, q: !TaskQueue}|null)} */
  2594. this.pending_ = null;
  2595. /** @private {TaskQueue} */
  2596. this.subQ_ = null;
  2597. /** @private {TaskQueueState} */
  2598. this.state_ = TaskQueueState.NEW;
  2599. /** @private {!Set<!ManagedPromise>} */
  2600. this.unhandledRejections_ = new Set();
  2601. }
  2602. /** @override */
  2603. toString() {
  2604. return 'TaskQueue::' + getUid(this);
  2605. }
  2606. /**
  2607. * @param {!ManagedPromise} promise .
  2608. */
  2609. addUnhandledRejection(promise) {
  2610. // TODO: node 4.0.0+
  2611. vlog(2, () => this + ' registering unhandled rejection: ' + promise, this);
  2612. this.unhandledRejections_.add(promise);
  2613. }
  2614. /**
  2615. * @param {!ManagedPromise} promise .
  2616. */
  2617. clearUnhandledRejection(promise) {
  2618. var deleted = this.unhandledRejections_.delete(promise);
  2619. if (deleted) {
  2620. // TODO: node 4.0.0+
  2621. vlog(2, () => this + ' clearing unhandled rejection: ' + promise, this);
  2622. }
  2623. }
  2624. /**
  2625. * Enqueues a new task for execution.
  2626. * @param {!Task} task The task to enqueue.
  2627. * @throws {Error} If this instance has already started execution.
  2628. */
  2629. enqueue(task) {
  2630. if (this.state_ !== TaskQueueState.NEW) {
  2631. throw Error('TaskQueue has started: ' + this);
  2632. }
  2633. if (task.queue) {
  2634. throw Error('Task is already scheduled in another queue');
  2635. }
  2636. this.tasks_.push(task);
  2637. task.queue = this;
  2638. ON_CANCEL_HANDLER.set(
  2639. task.promise,
  2640. (e) => this.onTaskCancelled_(task, e));
  2641. vlog(1, () => this + '.enqueue(' + task + ')', this);
  2642. vlog(2, () => this.flow_.toString(), this);
  2643. }
  2644. /**
  2645. * Schedules the callbacks registered on the given promise in this queue.
  2646. *
  2647. * @param {!ManagedPromise} promise the promise whose callbacks should be
  2648. * registered as interrupts in this task queue.
  2649. * @throws {Error} if this queue has already finished.
  2650. */
  2651. scheduleCallbacks(promise) {
  2652. if (this.state_ === TaskQueueState.FINISHED) {
  2653. throw new Error('cannot interrupt a finished q(' + this + ')');
  2654. }
  2655. if (this.pending_ && this.pending_.task.promise === promise) {
  2656. this.pending_.task.promise.queue_ = null;
  2657. this.pending_ = null;
  2658. asyncRun(() => this.executeNext_());
  2659. }
  2660. if (!promise.callbacks_) {
  2661. return;
  2662. }
  2663. promise.callbacks_.forEach(function(cb) {
  2664. cb.blocked = false;
  2665. if (cb.queue) {
  2666. return;
  2667. }
  2668. ON_CANCEL_HANDLER.set(
  2669. cb.promise,
  2670. (e) => this.onTaskCancelled_(cb, e));
  2671. if (cb.queue === this && this.tasks_.indexOf(cb) !== -1) {
  2672. return;
  2673. }
  2674. if (cb.queue) {
  2675. cb.queue.dropTask_(cb);
  2676. }
  2677. cb.queue = this;
  2678. if (!this.interrupts_) {
  2679. this.interrupts_ = [];
  2680. }
  2681. this.interrupts_.push(cb);
  2682. }, this);
  2683. promise.callbacks_ = null;
  2684. vlog(2, () => this + ' interrupted\n' + this.flow_, this);
  2685. }
  2686. /**
  2687. * Starts executing tasks in this queue. Once called, no further tasks may
  2688. * be {@linkplain #enqueue() enqueued} with this instance.
  2689. *
  2690. * @throws {Error} if this queue has already been started.
  2691. */
  2692. start() {
  2693. if (this.state_ !== TaskQueueState.NEW) {
  2694. throw new Error('TaskQueue has already started');
  2695. }
  2696. // Always asynchronously execute next, even if there doesn't look like
  2697. // there is anything in the queue. This will catch pending unhandled
  2698. // rejections that were registered before start was called.
  2699. asyncRun(() => this.executeNext_());
  2700. }
  2701. /**
  2702. * Aborts this task queue. If there are any scheduled tasks, they are silently
  2703. * cancelled and discarded (their callbacks will never fire). If this queue
  2704. * has a _pending_ task, the abortion error is used to cancel that task.
  2705. * Otherwise, this queue will emit an error event.
  2706. *
  2707. * @param {*} error The abortion reason.
  2708. * @private
  2709. */
  2710. abort_(error) {
  2711. var cancellation;
  2712. if (error instanceof FlowResetError) {
  2713. cancellation = error;
  2714. } else {
  2715. cancellation = new DiscardedTaskError(error);
  2716. }
  2717. if (this.interrupts_ && this.interrupts_.length) {
  2718. this.interrupts_.forEach((t) => t.reject(cancellation));
  2719. this.interrupts_ = [];
  2720. }
  2721. if (this.tasks_ && this.tasks_.length) {
  2722. this.tasks_.forEach((t) => t.reject(cancellation));
  2723. this.tasks_ = [];
  2724. }
  2725. // Now that all of the remaining tasks have been silently cancelled (e.g. no
  2726. // existing callbacks on those tasks will fire), clear the silence bit on
  2727. // the cancellation error. This ensures additional callbacks registered in
  2728. // the future will actually execute.
  2729. cancellation.silent_ = false;
  2730. if (this.pending_) {
  2731. vlog(2, () => this + '.abort(); cancelling pending task', this);
  2732. this.pending_.task.promise.cancel(
  2733. /** @type {!CancellationError} */(error));
  2734. } else {
  2735. vlog(2, () => this + '.abort(); emitting error event', this);
  2736. this.emit('error', error, this);
  2737. }
  2738. }
  2739. /** @private */
  2740. executeNext_() {
  2741. if (this.state_ === TaskQueueState.FINISHED) {
  2742. return;
  2743. }
  2744. this.state_ = TaskQueueState.STARTED;
  2745. if (this.pending_ !== null || this.processUnhandledRejections_()) {
  2746. return;
  2747. }
  2748. var task;
  2749. do {
  2750. task = this.getNextTask_();
  2751. } while (task && !isPending(task.promise));
  2752. if (!task) {
  2753. this.state_ = TaskQueueState.FINISHED;
  2754. this.tasks_ = [];
  2755. this.interrupts_ = null;
  2756. vlog(2, () => this + '.emit(end)', this);
  2757. this.emit('end', this);
  2758. return;
  2759. }
  2760. let result = undefined;
  2761. this.subQ_ = new TaskQueue(this.flow_);
  2762. this.subQ_.once('end', () => { // On task completion.
  2763. this.subQ_ = null;
  2764. this.pending_ && this.pending_.task.resolve(result);
  2765. });
  2766. this.subQ_.once('error', e => { // On task failure.
  2767. this.subQ_ = null;
  2768. if (Thenable.isImplementation(result)) {
  2769. result.cancel(CancellationError.wrap(e));
  2770. }
  2771. this.pending_ && this.pending_.task.reject(e);
  2772. });
  2773. vlog(2, () => `${this} created ${this.subQ_} for ${task}`);
  2774. try {
  2775. this.pending_ = {task: task, q: this.subQ_};
  2776. task.promise.queue_ = this;
  2777. result = this.subQ_.execute_(task.execute);
  2778. this.subQ_.start();
  2779. } catch (ex) {
  2780. this.subQ_.abort_(ex);
  2781. }
  2782. }
  2783. /**
  2784. * @param {!Function} fn .
  2785. * @return {T} .
  2786. * @template T
  2787. * @private
  2788. */
  2789. execute_(fn) {
  2790. try {
  2791. activeFlows.push(this.flow_);
  2792. this.flow_.activeQueue_ = this;
  2793. return fn();
  2794. } finally {
  2795. this.flow_.activeQueue_ = null;
  2796. activeFlows.pop();
  2797. }
  2798. }
  2799. /**
  2800. * Process any unhandled rejections registered with this task queue. If there
  2801. * is a rejection, this queue will be aborted with the rejection error. If
  2802. * there are multiple rejections registered, this queue will be aborted with
  2803. * a {@link MultipleUnhandledRejectionError}.
  2804. * @return {boolean} whether there was an unhandled rejection.
  2805. * @private
  2806. */
  2807. processUnhandledRejections_() {
  2808. if (!this.unhandledRejections_.size) {
  2809. return false;
  2810. }
  2811. var errors = new Set();
  2812. for (var rejection of this.unhandledRejections_) {
  2813. errors.add(rejection.value_);
  2814. }
  2815. this.unhandledRejections_.clear();
  2816. var errorToReport = errors.size === 1
  2817. ? errors.values().next().value
  2818. : new MultipleUnhandledRejectionError(errors);
  2819. vlog(1, () => this + ' aborting due to unhandled rejections', this);
  2820. if (this.flow_.propagateUnhandledRejections_) {
  2821. this.abort_(errorToReport);
  2822. return true;
  2823. } else {
  2824. vlog(1, 'error propagation disabled; reporting to control flow');
  2825. this.flow_.reportUncaughtException_(errorToReport);
  2826. return false;
  2827. }
  2828. }
  2829. /**
  2830. * @param {!Task} task The task to drop.
  2831. * @private
  2832. */
  2833. dropTask_(task) {
  2834. var index;
  2835. if (this.interrupts_) {
  2836. index = this.interrupts_.indexOf(task);
  2837. if (index != -1) {
  2838. task.queue = null;
  2839. this.interrupts_.splice(index, 1);
  2840. return;
  2841. }
  2842. }
  2843. index = this.tasks_.indexOf(task);
  2844. if (index != -1) {
  2845. task.queue = null;
  2846. this.tasks_.splice(index, 1);
  2847. }
  2848. }
  2849. /**
  2850. * @param {!Task} task The task that was cancelled.
  2851. * @param {!CancellationError} reason The cancellation reason.
  2852. * @private
  2853. */
  2854. onTaskCancelled_(task, reason) {
  2855. if (this.pending_ && this.pending_.task === task) {
  2856. this.pending_.q.abort_(reason);
  2857. } else {
  2858. this.dropTask_(task);
  2859. }
  2860. }
  2861. /**
  2862. * @return {(Task|undefined)} the next task scheduled within this queue,
  2863. * if any.
  2864. * @private
  2865. */
  2866. getNextTask_() {
  2867. var task = undefined;
  2868. while (true) {
  2869. if (this.interrupts_) {
  2870. task = this.interrupts_.shift();
  2871. }
  2872. if (!task && this.tasks_) {
  2873. task = this.tasks_.shift();
  2874. }
  2875. if (task && task.blocked) {
  2876. vlog(2, () => this + ' skipping blocked task ' + task, this);
  2877. task.queue = null;
  2878. task = null;
  2879. // TODO: recurse when tail-call optimization is available in node.
  2880. } else {
  2881. break;
  2882. }
  2883. }
  2884. return task;
  2885. }
  2886. }
  2887. /**
  2888. * The default flow to use if no others are active.
  2889. * @type {ControlFlow}
  2890. */
  2891. var defaultFlow;
  2892. /**
  2893. * A stack of active control flows, with the top of the stack used to schedule
  2894. * commands. When there are multiple flows on the stack, the flow at index N
  2895. * represents a callback triggered within a task owned by the flow at index
  2896. * N-1.
  2897. * @type {!Array<!ControlFlow>}
  2898. */
  2899. var activeFlows = [];
  2900. /**
  2901. * Changes the default flow to use when no others are active.
  2902. * @param {!ControlFlow} flow The new default flow.
  2903. * @throws {Error} If the default flow is not currently active.
  2904. */
  2905. function setDefaultFlow(flow) {
  2906. if (!usePromiseManager()) {
  2907. throw Error(
  2908. 'You may not change set the control flow when the promise'
  2909. +' manager is disabled');
  2910. }
  2911. if (activeFlows.length) {
  2912. throw Error('You may only change the default flow while it is active');
  2913. }
  2914. defaultFlow = flow;
  2915. }
  2916. /**
  2917. * @return {!ControlFlow} The currently active control flow.
  2918. * @suppress {checkTypes}
  2919. */
  2920. function controlFlow() {
  2921. if (!usePromiseManager()) {
  2922. return SIMPLE_SCHEDULER;
  2923. }
  2924. if (activeFlows.length) {
  2925. return activeFlows[activeFlows.length - 1];
  2926. }
  2927. if (!defaultFlow) {
  2928. defaultFlow = new ControlFlow;
  2929. }
  2930. return defaultFlow;
  2931. }
  2932. /**
  2933. * Creates a new control flow. The provided callback will be invoked as the
  2934. * first task within the new flow, with the flow as its sole argument. Returns
  2935. * a promise that resolves to the callback result.
  2936. * @param {function(!ControlFlow)} callback The entry point
  2937. * to the newly created flow.
  2938. * @return {!Thenable} A promise that resolves to the callback result.
  2939. */
  2940. function createFlow(callback) {
  2941. var flow = new ControlFlow;
  2942. return flow.execute(function() {
  2943. return callback(flow);
  2944. });
  2945. }
  2946. /**
  2947. * Tests is a function is a generator.
  2948. * @param {!Function} fn The function to test.
  2949. * @return {boolean} Whether the function is a generator.
  2950. */
  2951. function isGenerator(fn) {
  2952. return fn.constructor.name === 'GeneratorFunction';
  2953. }
  2954. /**
  2955. * Consumes a {@code GeneratorFunction}. Each time the generator yields a
  2956. * promise, this function will wait for it to be fulfilled before feeding the
  2957. * fulfilled value back into {@code next}. Likewise, if a yielded promise is
  2958. * rejected, the rejection error will be passed to {@code throw}.
  2959. *
  2960. * __Example 1:__ the Fibonacci Sequence.
  2961. *
  2962. * promise.consume(function* fibonacci() {
  2963. * var n1 = 1, n2 = 1;
  2964. * for (var i = 0; i < 4; ++i) {
  2965. * var tmp = yield n1 + n2;
  2966. * n1 = n2;
  2967. * n2 = tmp;
  2968. * }
  2969. * return n1 + n2;
  2970. * }).then(function(result) {
  2971. * console.log(result); // 13
  2972. * });
  2973. *
  2974. * __Example 2:__ a generator that throws.
  2975. *
  2976. * promise.consume(function* () {
  2977. * yield promise.delayed(250).then(function() {
  2978. * throw Error('boom');
  2979. * });
  2980. * }).catch(function(e) {
  2981. * console.log(e.toString()); // Error: boom
  2982. * });
  2983. *
  2984. * @param {!Function} generatorFn The generator function to execute.
  2985. * @param {Object=} opt_self The object to use as "this" when invoking the
  2986. * initial generator.
  2987. * @param {...*} var_args Any arguments to pass to the initial generator.
  2988. * @return {!Thenable<?>} A promise that will resolve to the
  2989. * generator's final result.
  2990. * @throws {TypeError} If the given function is not a generator.
  2991. */
  2992. function consume(generatorFn, opt_self, ...var_args) {
  2993. if (!isGenerator(generatorFn)) {
  2994. throw new TypeError('Input is not a GeneratorFunction: ' +
  2995. generatorFn.constructor.name);
  2996. }
  2997. let ret;
  2998. return ret = createPromise((resolve, reject) => {
  2999. let generator = generatorFn.apply(opt_self, var_args);
  3000. callNext();
  3001. /** @param {*=} opt_value . */
  3002. function callNext(opt_value) {
  3003. pump(generator.next, opt_value);
  3004. }
  3005. /** @param {*=} opt_error . */
  3006. function callThrow(opt_error) {
  3007. pump(generator.throw, opt_error);
  3008. }
  3009. function pump(fn, opt_arg) {
  3010. if (ret instanceof ManagedPromise && !isPending(ret)) {
  3011. return; // Deferred was cancelled; silently abort.
  3012. }
  3013. try {
  3014. var result = fn.call(generator, opt_arg);
  3015. } catch (ex) {
  3016. reject(ex);
  3017. return;
  3018. }
  3019. if (result.done) {
  3020. resolve(result.value);
  3021. return;
  3022. }
  3023. asap(result.value, callNext, callThrow);
  3024. }
  3025. });
  3026. }
  3027. // PUBLIC API
  3028. module.exports = {
  3029. CancellableThenable: CancellableThenable,
  3030. CancellationError: CancellationError,
  3031. ControlFlow: ControlFlow,
  3032. Deferred: Deferred,
  3033. MultipleUnhandledRejectionError: MultipleUnhandledRejectionError,
  3034. Thenable: Thenable,
  3035. Promise: ManagedPromise,
  3036. Resolver: Resolver,
  3037. Scheduler: Scheduler,
  3038. all: all,
  3039. asap: asap,
  3040. captureStackTrace: captureStackTrace,
  3041. checkedNodeCall: checkedNodeCall,
  3042. consume: consume,
  3043. controlFlow: controlFlow,
  3044. createFlow: createFlow,
  3045. createPromise: createPromise,
  3046. defer: defer,
  3047. delayed: delayed,
  3048. filter: filter,
  3049. finally: thenFinally,
  3050. fulfilled: fulfilled,
  3051. fullyResolved: fullyResolved,
  3052. isGenerator: isGenerator,
  3053. isPromise: isPromise,
  3054. map: map,
  3055. rejected: rejected,
  3056. setDefaultFlow: setDefaultFlow,
  3057. when: when,
  3058. /**
  3059. * Indicates whether the promise manager is currently enabled. When disabled,
  3060. * attempting to use the {@link ControlFlow} or {@link ManagedPromise Promise}
  3061. * classes will generate an error.
  3062. *
  3063. * The promise manager is currently enabled by default, but may be disabled
  3064. * by setting the environment variable `SELENIUM_PROMISE_MANAGER=0` or by
  3065. * setting this property to false. Setting this property will always take
  3066. * precedence over the use of the environment variable.
  3067. *
  3068. * @return {boolean} Whether the promise manager is enabled.
  3069. * @see <https://github.com/SeleniumHQ/selenium/issues/2969>
  3070. */
  3071. get USE_PROMISE_MANAGER() { return usePromiseManager(); },
  3072. set USE_PROMISE_MANAGER(/** boolean */value) { USE_PROMISE_MANAGER = value; },
  3073. get LONG_STACK_TRACES() { return LONG_STACK_TRACES; },
  3074. set LONG_STACK_TRACES(v) { LONG_STACK_TRACES = v; },
  3075. };