selenium-webdriver 3.6.0 → 4.0.0-alpha.1

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