| 1 | // Copyright 2011 Software Freedom Conservancy. All Rights Reserved. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | /** |
| 16 | * @license Portions of this code are from the Dojo toolkit, received under the |
| 17 | * BSD License: |
| 18 | * Redistribution and use in source and binary forms, with or without |
| 19 | * modification, are permitted provided that the following conditions are met: |
| 20 | * |
| 21 | * * Redistributions of source code must retain the above copyright notice, |
| 22 | * this list of conditions and the following disclaimer. |
| 23 | * * Redistributions in binary form must reproduce the above copyright notice, |
| 24 | * this list of conditions and the following disclaimer in the documentation |
| 25 | * and/or other materials provided with the distribution. |
| 26 | * * Neither the name of the Dojo Foundation nor the names of its contributors |
| 27 | * may be used to endorse or promote products derived from this software |
| 28 | * without specific prior written permission. |
| 29 | * |
| 30 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 31 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 32 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 33 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE |
| 34 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 35 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 36 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 37 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 38 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 39 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 40 | * POSSIBILITY OF SUCH DAMAGE. |
| 41 | */ |
| 42 | |
| 43 | /** |
| 44 | * @fileoverview A promise implementation based on the CommonJS promise/A and |
| 45 | * promise/B proposals. For more information, see |
| 46 | * http://wiki.commonjs.org/wiki/Promises. |
| 47 | */ |
| 48 | |
| 49 | goog.provide('webdriver.promise'); |
| 50 | goog.provide('webdriver.promise.ControlFlow'); |
| 51 | goog.provide('webdriver.promise.ControlFlow.Timer'); |
| 52 | goog.provide('webdriver.promise.Deferred'); |
| 53 | goog.provide('webdriver.promise.Promise'); |
| 54 | goog.provide('webdriver.promise.Thenable'); |
| 55 | |
| 56 | goog.require('goog.array'); |
| 57 | goog.require('goog.debug.Error'); |
| 58 | goog.require('goog.object'); |
| 59 | goog.require('webdriver.EventEmitter'); |
| 60 | goog.require('webdriver.stacktrace.Snapshot'); |
| 61 | |
| 62 | |
| 63 | |
| 64 | /** |
| 65 | * Thenable is a promise-like object with a {@code then} method which may be |
| 66 | * used to schedule callbacks on a promised value. |
| 67 | * |
| 68 | * @interface |
| 69 | * @template T |
| 70 | */ |
| 71 | webdriver.promise.Thenable = function() {}; |
| 72 | |
| 73 | |
| 74 | /** |
| 75 | * Cancels the computation of this promise's value, rejecting the promise in the |
| 76 | * process. This method is a no-op if the promise has alreayd been resolved. |
| 77 | * |
| 78 | * @param {*=} opt_reason The reason this promise is being cancelled. If not an |
| 79 | * {@code Error}, one will be created using the value's string |
| 80 | * representation. |
| 81 | */ |
| 82 | webdriver.promise.Thenable.prototype.cancel = function(opt_reason) {}; |
| 83 | |
| 84 | |
| 85 | /** @return {boolean} Whether this promise's value is still being computed. */ |
| 86 | webdriver.promise.Thenable.prototype.isPending = function() {}; |
| 87 | |
| 88 | |
| 89 | /** |
| 90 | * Registers listeners for when this instance is resolved. |
| 91 | * |
| 92 | * @param {?(function(T): (R|webdriver.promise.Promise.<R>))=} opt_callback The |
| 93 | * function to call if this promise is successfully resolved. The function |
| 94 | * should expect a single argument: the promise's resolved value. |
| 95 | * @param {?(function(*): (R|webdriver.promise.Promise.<R>))=} opt_errback The |
| 96 | * function to call if this promise is rejected. The function should expect |
| 97 | * a single argument: the rejection reason. |
| 98 | * @return {!webdriver.promise.Promise.<R>} A new promise which will be |
| 99 | * resolved with the result of the invoked callback. |
| 100 | * @template R |
| 101 | */ |
| 102 | webdriver.promise.Thenable.prototype.then = function( |
| 103 | opt_callback, opt_errback) {}; |
| 104 | |
| 105 | |
| 106 | /** |
| 107 | * Registers a listener for when this promise is rejected. This is synonymous |
| 108 | * with the {@code catch} clause in a synchronous API: |
| 109 | * <pre><code> |
| 110 | * // Synchronous API: |
| 111 | * try { |
| 112 | * doSynchronousWork(); |
| 113 | * } catch (ex) { |
| 114 | * console.error(ex); |
| 115 | * } |
| 116 | * |
| 117 | * // Asynchronous promise API: |
| 118 | * doAsynchronousWork().thenCatch(function(ex) { |
| 119 | * console.error(ex); |
| 120 | * }); |
| 121 | * </code></pre> |
| 122 | * |
| 123 | * @param {function(*): (R|webdriver.promise.Promise.<R>)} errback The function |
| 124 | * to call if this promise is rejected. The function should expect a single |
| 125 | * argument: the rejection reason. |
| 126 | * @return {!webdriver.promise.Promise.<R>} A new promise which will be |
| 127 | * resolved with the result of the invoked callback. |
| 128 | * @template R |
| 129 | */ |
| 130 | webdriver.promise.Thenable.prototype.thenCatch = function(errback) {}; |
| 131 | |
| 132 | |
| 133 | /** |
| 134 | * Registers a listener to invoke when this promise is resolved, regardless |
| 135 | * of whether the promise's value was successfully computed. This function |
| 136 | * is synonymous with the {@code finally} clause in a synchronous API: |
| 137 | * <pre><code> |
| 138 | * // Synchronous API: |
| 139 | * try { |
| 140 | * doSynchronousWork(); |
| 141 | * } finally { |
| 142 | * cleanUp(); |
| 143 | * } |
| 144 | * |
| 145 | * // Asynchronous promise API: |
| 146 | * doAsynchronousWork().thenFinally(cleanUp); |
| 147 | * </code></pre> |
| 148 | * |
| 149 | * <b>Note:</b> similar to the {@code finally} clause, if the registered |
| 150 | * callback returns a rejected promise or throws an error, it will silently |
| 151 | * replace the rejection error (if any) from this promise: |
| 152 | * <pre><code> |
| 153 | * try { |
| 154 | * throw Error('one'); |
| 155 | * } finally { |
| 156 | * throw Error('two'); // Hides Error: one |
| 157 | * } |
| 158 | * |
| 159 | * webdriver.promise.rejected(Error('one')) |
| 160 | * .thenFinally(function() { |
| 161 | * throw Error('two'); // Hides Error: one |
| 162 | * }); |
| 163 | * </code></pre> |
| 164 | * |
| 165 | * |
| 166 | * @param {function(): (R|webdriver.promise.Promise.<R>)} callback The function |
| 167 | * to call when this promise is resolved. |
| 168 | * @return {!webdriver.promise.Promise.<R>} A promise that will be fulfilled |
| 169 | * with the callback result. |
| 170 | * @template R |
| 171 | */ |
| 172 | webdriver.promise.Thenable.prototype.thenFinally = function(callback) {}; |
| 173 | |
| 174 | |
| 175 | /** |
| 176 | * Property used to flag constructor's as implementing the Thenable interface |
| 177 | * for runtime type checking. |
| 178 | * @private {string} |
| 179 | * @const |
| 180 | */ |
| 181 | webdriver.promise.Thenable.IMPLEMENTED_BY_PROP_ = '$webdriver_Thenable'; |
| 182 | |
| 183 | |
| 184 | /** |
| 185 | * Adds a property to a class prototype to allow runtime checks of whether |
| 186 | * instances of that class implement the Thenable interface. This function will |
| 187 | * also ensure the prototype's {@code then} function is exported from compiled |
| 188 | * code. |
| 189 | * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The |
| 190 | * constructor whose prototype to modify. |
| 191 | */ |
| 192 | webdriver.promise.Thenable.addImplementation = function(ctor) { |
| 193 | // Based on goog.promise.Thenable.isImplementation. |
| 194 | ctor.prototype['then'] = ctor.prototype.then; |
| 195 | try { |
| 196 | // Old IE7 does not support defineProperty; IE8 only supports it for |
| 197 | // DOM elements. |
| 198 | Object.defineProperty( |
| 199 | ctor.prototype, |
| 200 | webdriver.promise.Thenable.IMPLEMENTED_BY_PROP_, |
| 201 | {'value': true, 'enumerable': false}); |
| 202 | } catch (ex) { |
| 203 | ctor.prototype[webdriver.promise.Thenable.IMPLEMENTED_BY_PROP_] = true; |
| 204 | } |
| 205 | }; |
| 206 | |
| 207 | |
| 208 | /** |
| 209 | * Checks if an object has been tagged for implementing the Thenable interface |
| 210 | * as defined by {@link webdriver.promise.Thenable.addImplementation}. |
| 211 | * @param {*} object The object to test. |
| 212 | * @return {boolean} Whether the object is an implementation of the Thenable |
| 213 | * interface. |
| 214 | */ |
| 215 | webdriver.promise.Thenable.isImplementation = function(object) { |
| 216 | // Based on goog.promise.Thenable.isImplementation. |
| 217 | if (!object) { |
| 218 | return false; |
| 219 | } |
| 220 | try { |
| 221 | return !!object[webdriver.promise.Thenable.IMPLEMENTED_BY_PROP_]; |
| 222 | } catch (e) { |
| 223 | return false; // Property access seems to be forbidden. |
| 224 | } |
| 225 | }; |
| 226 | |
| 227 | |
| 228 | |
| 229 | /** |
| 230 | * Represents the eventual value of a completed operation. Each promise may be |
| 231 | * in one of three states: pending, resolved, or rejected. Each promise starts |
| 232 | * in the pending state and may make a single transition to either a |
| 233 | * fulfilled or rejected state, at which point the promise is considered |
| 234 | * resolved. |
| 235 | * |
| 236 | * @constructor |
| 237 | * @implements {webdriver.promise.Thenable.<T>} |
| 238 | * @template T |
| 239 | * @see http://promises-aplus.github.io/promises-spec/ |
| 240 | */ |
| 241 | webdriver.promise.Promise = function() {}; |
| 242 | webdriver.promise.Thenable.addImplementation(webdriver.promise.Promise); |
| 243 | |
| 244 | |
| 245 | /** @override */ |
| 246 | webdriver.promise.Promise.prototype.cancel = function(reason) { |
| 247 | throw new TypeError('Unimplemented function: "cancel"'); |
| 248 | }; |
| 249 | |
| 250 | |
| 251 | /** @override */ |
| 252 | webdriver.promise.Promise.prototype.isPending = function() { |
| 253 | throw new TypeError('Unimplemented function: "isPending"'); |
| 254 | }; |
| 255 | |
| 256 | |
| 257 | /** @override */ |
| 258 | webdriver.promise.Promise.prototype.then = function( |
| 259 | opt_callback, opt_errback) { |
| 260 | throw new TypeError('Unimplemented function: "then"'); |
| 261 | }; |
| 262 | |
| 263 | |
| 264 | /** @override */ |
| 265 | webdriver.promise.Promise.prototype.thenCatch = function(errback) { |
| 266 | return this.then(null, errback); |
| 267 | }; |
| 268 | |
| 269 | |
| 270 | /** @override */ |
| 271 | webdriver.promise.Promise.prototype.thenFinally = function(callback) { |
| 272 | return this.then(callback, function(err) { |
| 273 | var value = callback(); |
| 274 | if (webdriver.promise.isPromise(value)) { |
| 275 | return value.then(function() { |
| 276 | throw err; |
| 277 | }); |
| 278 | } |
| 279 | throw err; |
| 280 | }); |
| 281 | }; |
| 282 | |
| 283 | |
| 284 | |
| 285 | /** |
| 286 | * Represents a value that will be resolved at some point in the future. This |
| 287 | * class represents the protected "producer" half of a Promise - each Deferred |
| 288 | * has a {@code promise} property that may be returned to consumers for |
| 289 | * registering callbacks, reserving the ability to resolve the deferred to the |
| 290 | * producer. |
| 291 | * |
| 292 | * <p>If this Deferred is rejected and there are no listeners registered before |
| 293 | * the next turn of the event loop, the rejection will be passed to the |
| 294 | * {@link webdriver.promise.ControlFlow} as an unhandled failure. |
| 295 | * |
| 296 | * <p>If this Deferred is cancelled, the cancellation reason will be forward to |
| 297 | * the Deferred's canceller function (if provided). The canceller may return a |
| 298 | * truth-y value to override the reason provided for rejection. |
| 299 | * |
| 300 | * @param {Function=} opt_canceller Function to call when cancelling the |
| 301 | * computation of this instance's value. |
| 302 | * @param {webdriver.promise.ControlFlow=} opt_flow The control flow |
| 303 | * this instance was created under. This should only be provided during |
| 304 | * unit tests. |
| 305 | * @constructor |
| 306 | * @extends {webdriver.promise.Promise.<T>} |
| 307 | * @template T |
| 308 | */ |
| 309 | webdriver.promise.Deferred = function(opt_canceller, opt_flow) { |
| 310 | /* NOTE: This class's implementation diverges from the prototypical style |
| 311 | * used in the rest of the atoms library. This was done intentionally to |
| 312 | * protect the internal Deferred state from consumers, as outlined by |
| 313 | * http://wiki.commonjs.org/wiki/Promises |
| 314 | */ |
| 315 | goog.base(this); |
| 316 | |
| 317 | var flow = opt_flow || webdriver.promise.controlFlow(); |
| 318 | |
| 319 | /** |
| 320 | * The listeners registered with this Deferred. Each element in the list will |
| 321 | * be a 3-tuple of the callback function, errback function, and the |
| 322 | * corresponding deferred object. |
| 323 | * @type {!Array.<!webdriver.promise.Deferred.Listener_>} |
| 324 | */ |
| 325 | var listeners = []; |
| 326 | |
| 327 | /** |
| 328 | * Whether this Deferred's resolution was ever handled by a listener. |
| 329 | * If the Deferred is rejected and its value is not handled by a listener |
| 330 | * before the next turn of the event loop, the error will be passed to the |
| 331 | * global error handler. |
| 332 | * @type {boolean} |
| 333 | */ |
| 334 | var handled = false; |
| 335 | |
| 336 | /** |
| 337 | * Key for the timeout used to delay reproting an unhandled rejection to the |
| 338 | * parent {@link webdriver.promise.ControlFlow}. |
| 339 | * @type {?number} |
| 340 | */ |
| 341 | var pendingRejectionKey = null; |
| 342 | |
| 343 | /** |
| 344 | * This Deferred's current state. |
| 345 | * @type {!webdriver.promise.Deferred.State_} |
| 346 | */ |
| 347 | var state = webdriver.promise.Deferred.State_.PENDING; |
| 348 | |
| 349 | /** |
| 350 | * This Deferred's resolved value; set when the state transitions from |
| 351 | * {@code webdriver.promise.Deferred.State_.PENDING}. |
| 352 | * @type {*} |
| 353 | */ |
| 354 | var value; |
| 355 | |
| 356 | /** @return {boolean} Whether this promise's value is still pending. */ |
| 357 | function isPending() { |
| 358 | return state == webdriver.promise.Deferred.State_.PENDING; |
| 359 | } |
| 360 | |
| 361 | /** |
| 362 | * Removes all of the listeners previously registered on this deferred. |
| 363 | * @throws {Error} If this deferred has already been resolved. |
| 364 | */ |
| 365 | function removeAll() { |
| 366 | listeners = []; |
| 367 | } |
| 368 | |
| 369 | /** |
| 370 | * Resolves this deferred. If the new value is a promise, this function will |
| 371 | * wait for it to be resolved before notifying the registered listeners. |
| 372 | * @param {!webdriver.promise.Deferred.State_} newState The deferred's new |
| 373 | * state. |
| 374 | * @param {*} newValue The deferred's new value. |
| 375 | */ |
| 376 | function resolve(newState, newValue) { |
| 377 | if (webdriver.promise.Deferred.State_.PENDING !== state) { |
| 378 | return; |
| 379 | } |
| 380 | |
| 381 | if (newValue === self) { |
| 382 | // See promise a+, 2.3.1 |
| 383 | // http://promises-aplus.github.io/promises-spec/#point-48 |
| 384 | throw TypeError('A promise may not resolve to itself'); |
| 385 | } |
| 386 | |
| 387 | state = webdriver.promise.Deferred.State_.BLOCKED; |
| 388 | |
| 389 | if (webdriver.promise.isPromise(newValue)) { |
| 390 | var onFulfill = goog.partial(notifyAll, newState); |
| 391 | var onReject = goog.partial( |
| 392 | notifyAll, webdriver.promise.Deferred.State_.REJECTED); |
| 393 | if (newValue instanceof webdriver.promise.Deferred) { |
| 394 | newValue.then(onFulfill, onReject); |
| 395 | } else { |
| 396 | webdriver.promise.asap(newValue, onFulfill, onReject); |
| 397 | } |
| 398 | |
| 399 | } else { |
| 400 | notifyAll(newState, newValue); |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | /** |
| 405 | * Notifies all of the listeners registered with this Deferred that its state |
| 406 | * has changed. |
| 407 | * @param {!webdriver.promise.Deferred.State_} newState The deferred's new |
| 408 | * state. |
| 409 | * @param {*} newValue The deferred's new value. |
| 410 | */ |
| 411 | function notifyAll(newState, newValue) { |
| 412 | if (newState === webdriver.promise.Deferred.State_.REJECTED && |
| 413 | // We cannot check instanceof Error since the object may have been |
| 414 | // created in a different JS context. |
| 415 | goog.isObject(newValue) && goog.isString(newValue.message)) { |
| 416 | newValue = flow.annotateError(/** @type {!Error} */(newValue)); |
| 417 | } |
| 418 | |
| 419 | state = newState; |
| 420 | value = newValue; |
| 421 | while (listeners.length) { |
| 422 | notify(listeners.shift()); |
| 423 | } |
| 424 | |
| 425 | if (!handled && state == webdriver.promise.Deferred.State_.REJECTED) { |
| 426 | flow.pendingRejections_ += 1; |
| 427 | pendingRejectionKey = flow.timer.setTimeout(function() { |
| 428 | pendingRejectionKey = null; |
| 429 | flow.pendingRejections_ -= 1; |
| 430 | flow.abortFrame_(value); |
| 431 | }, 0); |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | /** |
| 436 | * Notifies a single listener of this Deferred's change in state. |
| 437 | * @param {!webdriver.promise.Deferred.Listener_} listener The listener to |
| 438 | * notify. |
| 439 | */ |
| 440 | function notify(listener) { |
| 441 | var func = state == webdriver.promise.Deferred.State_.RESOLVED ? |
| 442 | listener.callback : listener.errback; |
| 443 | if (func) { |
| 444 | flow.runInNewFrame_(goog.partial(func, value), |
| 445 | listener.fulfill, listener.reject); |
| 446 | } else if (state == webdriver.promise.Deferred.State_.REJECTED) { |
| 447 | listener.reject(value); |
| 448 | } else { |
| 449 | listener.fulfill(value); |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | /** |
| 454 | * The consumer promise for this instance. Provides protected access to the |
| 455 | * callback registering functions. |
| 456 | * @type {!webdriver.promise.Promise.<T>} |
| 457 | */ |
| 458 | var promise = new webdriver.promise.Promise(); |
| 459 | |
| 460 | /** |
| 461 | * Registers a callback on this Deferred. |
| 462 | * |
| 463 | * @param {?(function(T): (R|webdriver.promise.Promise.<R>))=} opt_callback . |
| 464 | * @param {?(function(*): (R|webdriver.promise.Promise.<R>))=} opt_errback . |
| 465 | * @return {!webdriver.promise.Promise.<R>} A new promise representing the |
| 466 | * result of the callback. |
| 467 | * @template R |
| 468 | * @see webdriver.promise.Promise#then |
| 469 | */ |
| 470 | function then(opt_callback, opt_errback) { |
| 471 | // Avoid unnecessary allocations if we weren't given any callback functions. |
| 472 | if (!opt_callback && !opt_errback) { |
| 473 | return promise; |
| 474 | } |
| 475 | |
| 476 | // The moment a listener is registered, we consider this deferred to be |
| 477 | // handled; the callback must handle any rejection errors. |
| 478 | handled = true; |
| 479 | if (pendingRejectionKey !== null) { |
| 480 | flow.pendingRejections_ -= 1; |
| 481 | flow.timer.clearTimeout(pendingRejectionKey); |
| 482 | pendingRejectionKey = null; |
| 483 | } |
| 484 | |
| 485 | var deferred = new webdriver.promise.Deferred(cancel, flow); |
| 486 | var listener = { |
| 487 | callback: opt_callback, |
| 488 | errback: opt_errback, |
| 489 | fulfill: deferred.fulfill, |
| 490 | reject: deferred.reject |
| 491 | }; |
| 492 | |
| 493 | if (state == webdriver.promise.Deferred.State_.PENDING || |
| 494 | state == webdriver.promise.Deferred.State_.BLOCKED) { |
| 495 | listeners.push(listener); |
| 496 | } else { |
| 497 | notify(listener); |
| 498 | } |
| 499 | |
| 500 | return deferred.promise; |
| 501 | } |
| 502 | |
| 503 | var self = this; |
| 504 | |
| 505 | /** |
| 506 | * Resolves this promise with the given value. If the value is itself a |
| 507 | * promise and not a reference to this deferred, this instance will wait for |
| 508 | * it before resolving. |
| 509 | * @param {T=} opt_value The fulfilled value. |
| 510 | */ |
| 511 | function fulfill(opt_value) { |
| 512 | resolve(webdriver.promise.Deferred.State_.RESOLVED, opt_value); |
| 513 | } |
| 514 | |
| 515 | /** |
| 516 | * Rejects this promise. If the error is itself a promise, this instance will |
| 517 | * be chained to it and be rejected with the error's resolved value. |
| 518 | * @param {*=} opt_error The rejection reason, typically either a |
| 519 | * {@code Error} or a {@code string}. |
| 520 | */ |
| 521 | function reject(opt_error) { |
| 522 | resolve(webdriver.promise.Deferred.State_.REJECTED, opt_error); |
| 523 | } |
| 524 | |
| 525 | /** |
| 526 | * Attempts to cancel the computation of this instance's value. This attempt |
| 527 | * will silently fail if this instance has already resolved. |
| 528 | * @param {*=} opt_reason The reason for cancelling this promise. |
| 529 | */ |
| 530 | function cancel(opt_reason) { |
| 531 | if (!isPending()) { |
| 532 | return; |
| 533 | } |
| 534 | |
| 535 | if (opt_canceller) { |
| 536 | opt_reason = opt_canceller(opt_reason) || opt_reason; |
| 537 | } |
| 538 | |
| 539 | reject(opt_reason); |
| 540 | } |
| 541 | |
| 542 | this.promise = promise; |
| 543 | this.promise.then = this.then = then; |
| 544 | this.promise.cancel = this.cancel = cancel; |
| 545 | this.promise.isPending = this.isPending = isPending; |
| 546 | this.fulfill = fulfill; |
| 547 | this.reject = this.errback = reject; |
| 548 | |
| 549 | // Only expose this function to our internal classes. |
| 550 | // TODO: find a cleaner way of handling this. |
| 551 | if (this instanceof webdriver.promise.Task_) { |
| 552 | this.removeAll = removeAll; |
| 553 | } |
| 554 | |
| 555 | // Export symbols necessary for the contract on this object to work in |
| 556 | // compiled mode. |
| 557 | goog.exportProperty(this, 'then', this.then); |
| 558 | goog.exportProperty(this, 'cancel', cancel); |
| 559 | goog.exportProperty(this, 'fulfill', fulfill); |
| 560 | goog.exportProperty(this, 'reject', reject); |
| 561 | goog.exportProperty(this, 'isPending', isPending); |
| 562 | goog.exportProperty(this, 'promise', this.promise); |
| 563 | goog.exportProperty(this.promise, 'then', this.then); |
| 564 | goog.exportProperty(this.promise, 'cancel', cancel); |
| 565 | goog.exportProperty(this.promise, 'isPending', isPending); |
| 566 | }; |
| 567 | goog.inherits(webdriver.promise.Deferred, webdriver.promise.Promise); |
| 568 | |
| 569 | |
| 570 | /** |
| 571 | * Type definition for a listener registered on a Deferred object. |
| 572 | * @typedef {{callback:(Function|undefined), |
| 573 | * errback:(Function|undefined), |
| 574 | * fulfill: function(*), reject: function(*)}} |
| 575 | * @private |
| 576 | */ |
| 577 | webdriver.promise.Deferred.Listener_; |
| 578 | |
| 579 | |
| 580 | /** |
| 581 | * The three states a {@link webdriver.promise.Deferred} object may be in. |
| 582 | * @enum {number} |
| 583 | * @private |
| 584 | */ |
| 585 | webdriver.promise.Deferred.State_ = { |
| 586 | REJECTED: -1, |
| 587 | PENDING: 0, |
| 588 | BLOCKED: 1, |
| 589 | RESOLVED: 2 |
| 590 | }; |
| 591 | |
| 592 | |
| 593 | /** |
| 594 | * Tests if a value is an Error-like object. This is more than an straight |
| 595 | * instanceof check since the value may originate from another context. |
| 596 | * @param {*} value The value to test. |
| 597 | * @return {boolean} Whether the value is an error. |
| 598 | * @private |
| 599 | */ |
| 600 | webdriver.promise.isError_ = function(value) { |
| 601 | return value instanceof Error || |
| 602 | goog.isObject(value) && |
| 603 | (Object.prototype.toString.call(value) === '[object Error]' || |
| 604 | // A special test for goog.testing.JsUnitException. |
| 605 | value.isJsUnitException); |
| 606 | |
| 607 | }; |
| 608 | |
| 609 | |
| 610 | /** |
| 611 | * Determines whether a {@code value} should be treated as a promise. |
| 612 | * Any object whose "then" property is a function will be considered a promise. |
| 613 | * |
| 614 | * @param {*} value The value to test. |
| 615 | * @return {boolean} Whether the value is a promise. |
| 616 | */ |
| 617 | webdriver.promise.isPromise = function(value) { |
| 618 | return !!value && goog.isObject(value) && |
| 619 | // Use array notation so the Closure compiler does not obfuscate away our |
| 620 | // contract. |
| 621 | goog.isFunction(value['then']); |
| 622 | }; |
| 623 | |
| 624 | |
| 625 | /** |
| 626 | * Creates a promise that will be resolved at a set time in the future. |
| 627 | * @param {number} ms The amount of time, in milliseconds, to wait before |
| 628 | * resolving the promise. |
| 629 | * @return {!webdriver.promise.Promise} The promise. |
| 630 | */ |
| 631 | webdriver.promise.delayed = function(ms) { |
| 632 | var timer = webdriver.promise.controlFlow().timer; |
| 633 | var key; |
| 634 | var deferred = new webdriver.promise.Deferred(function() { |
| 635 | timer.clearTimeout(key); |
| 636 | }); |
| 637 | key = timer.setTimeout(deferred.fulfill, ms); |
| 638 | return deferred.promise; |
| 639 | }; |
| 640 | |
| 641 | |
| 642 | /** |
| 643 | * Creates a new deferred object. |
| 644 | * @param {Function=} opt_canceller Function to call when cancelling the |
| 645 | * computation of this instance's value. |
| 646 | * @return {!webdriver.promise.Deferred.<T>} The new deferred object. |
| 647 | * @template T |
| 648 | */ |
| 649 | webdriver.promise.defer = function(opt_canceller) { |
| 650 | return new webdriver.promise.Deferred(opt_canceller); |
| 651 | }; |
| 652 | |
| 653 | |
| 654 | /** |
| 655 | * Creates a promise that has been resolved with the given value. |
| 656 | * @param {T=} opt_value The resolved value. |
| 657 | * @return {!webdriver.promise.Promise.<T>} The resolved promise. |
| 658 | * @template T |
| 659 | */ |
| 660 | webdriver.promise.fulfilled = function(opt_value) { |
| 661 | if (opt_value instanceof webdriver.promise.Promise) { |
| 662 | return opt_value; |
| 663 | } |
| 664 | var deferred = new webdriver.promise.Deferred(); |
| 665 | deferred.fulfill(opt_value); |
| 666 | return deferred.promise; |
| 667 | }; |
| 668 | |
| 669 | |
| 670 | /** |
| 671 | * Creates a promise that has been rejected with the given reason. |
| 672 | * @param {*=} opt_reason The rejection reason; may be any value, but is |
| 673 | * usually an Error or a string. |
| 674 | * @return {!webdriver.promise.Promise.<T>} The rejected promise. |
| 675 | * @template T |
| 676 | */ |
| 677 | webdriver.promise.rejected = function(opt_reason) { |
| 678 | var deferred = new webdriver.promise.Deferred(); |
| 679 | deferred.reject(opt_reason); |
| 680 | return deferred.promise; |
| 681 | }; |
| 682 | |
| 683 | |
| 684 | /** |
| 685 | * Wraps a function that is assumed to be a node-style callback as its final |
| 686 | * argument. This callback takes two arguments: an error value (which will be |
| 687 | * null if the call succeeded), and the success value as the second argument. |
| 688 | * If the call fails, the returned promise will be rejected, otherwise it will |
| 689 | * be resolved with the result. |
| 690 | * @param {!Function} fn The function to wrap. |
| 691 | * @param {...?} var_args The arguments to apply to the function, excluding the |
| 692 | * final callback. |
| 693 | * @return {!webdriver.promise.Promise} A promise that will be resolved with the |
| 694 | * result of the provided function's callback. |
| 695 | */ |
| 696 | webdriver.promise.checkedNodeCall = function(fn, var_args) { |
| 697 | var deferred = new webdriver.promise.Deferred(function() { |
| 698 | throw Error('This Deferred may not be cancelled'); |
| 699 | }); |
| 700 | try { |
| 701 | var args = goog.array.slice(arguments, 1); |
| 702 | args.push(function(error, value) { |
| 703 | error ? deferred.reject(error) : deferred.fulfill(value); |
| 704 | }); |
| 705 | fn.apply(null, args); |
| 706 | } catch (ex) { |
| 707 | deferred.reject(ex); |
| 708 | } |
| 709 | return deferred.promise; |
| 710 | }; |
| 711 | |
| 712 | |
| 713 | /** |
| 714 | * Registers an observer on a promised {@code value}, returning a new promise |
| 715 | * that will be resolved when the value is. If {@code value} is not a promise, |
| 716 | * then the return promise will be immediately resolved. |
| 717 | * @param {*} value The value to observe. |
| 718 | * @param {Function=} opt_callback The function to call when the value is |
| 719 | * resolved successfully. |
| 720 | * @param {Function=} opt_errback The function to call when the value is |
| 721 | * rejected. |
| 722 | * @return {!webdriver.promise.Promise} A new promise. |
| 723 | */ |
| 724 | webdriver.promise.when = function(value, opt_callback, opt_errback) { |
| 725 | if (webdriver.promise.Thenable.isImplementation(value)) { |
| 726 | return value.then(opt_callback, opt_errback); |
| 727 | } |
| 728 | |
| 729 | var deferred = new webdriver.promise.Deferred(); |
| 730 | |
| 731 | webdriver.promise.asap(value, deferred.fulfill, deferred.reject); |
| 732 | |
| 733 | return deferred.then(opt_callback, opt_errback); |
| 734 | }; |
| 735 | |
| 736 | |
| 737 | /** |
| 738 | * Invokes the appropriate callback function as soon as a promised |
| 739 | * {@code value} is resolved. This function is similar to |
| 740 | * {@link webdriver.promise.when}, except it does not return a new promise. |
| 741 | * @param {*} value The value to observe. |
| 742 | * @param {Function} callback The function to call when the value is |
| 743 | * resolved successfully. |
| 744 | * @param {Function=} opt_errback The function to call when the value is |
| 745 | * rejected. |
| 746 | */ |
| 747 | webdriver.promise.asap = function(value, callback, opt_errback) { |
| 748 | if (webdriver.promise.isPromise(value)) { |
| 749 | value.then(callback, opt_errback); |
| 750 | |
| 751 | // Maybe a Dojo-like deferred object? |
| 752 | } else if (!!value && goog.isObject(value) && |
| 753 | goog.isFunction(value.addCallbacks)) { |
| 754 | value.addCallbacks(callback, opt_errback); |
| 755 | |
| 756 | // A raw value, return a resolved promise. |
| 757 | } else if (callback) { |
| 758 | callback(value); |
| 759 | } |
| 760 | }; |
| 761 | |
| 762 | |
| 763 | /** |
| 764 | * Given an array of promises, will return a promise that will be fulfilled |
| 765 | * with the fulfillment values of the input array's values. If any of the |
| 766 | * input array's promises are rejected, the returned promise will be rejected |
| 767 | * with the same reason. |
| 768 | * |
| 769 | * @param {!Array.<(T|!webdriver.promise.Promise.<T>)>} arr An array of |
| 770 | * promises to wait on. |
| 771 | * @return {!webdriver.promise.Promise.<!Array.<T>>} A promise that is |
| 772 | * fulfilled with an array containing the fulfilled values of the |
| 773 | * input array, or rejected with the same reason as the first |
| 774 | * rejected value. |
| 775 | * @template T |
| 776 | */ |
| 777 | webdriver.promise.all = function(arr) { |
| 778 | var n = arr.length; |
| 779 | if (!n) { |
| 780 | return webdriver.promise.fulfilled([]); |
| 781 | } |
| 782 | |
| 783 | var toFulfill = n; |
| 784 | var result = webdriver.promise.defer(); |
| 785 | var values = []; |
| 786 | |
| 787 | var onFulfill = function(index, value) { |
| 788 | values[index] = value; |
| 789 | toFulfill--; |
| 790 | if (toFulfill == 0) { |
| 791 | result.fulfill(values); |
| 792 | } |
| 793 | }; |
| 794 | |
| 795 | for (var i = 0; i < n; ++i) { |
| 796 | webdriver.promise.asap( |
| 797 | arr[i], goog.partial(onFulfill, i), result.reject); |
| 798 | } |
| 799 | |
| 800 | return result.promise; |
| 801 | }; |
| 802 | |
| 803 | |
| 804 | /** |
| 805 | * Calls a function for each element in an array and inserts the result into a |
| 806 | * new array, which is used as the fulfillment value of the promise returned |
| 807 | * by this function. |
| 808 | * |
| 809 | * <p>If the return value of the mapping function is a promise, this function |
| 810 | * will wait for it to be fulfilled before inserting it into the new array. |
| 811 | * |
| 812 | * <p>If the mapping function throws or returns a rejected promise, the |
| 813 | * promise returned by this function will be rejected with the same reason. |
| 814 | * Only the first failure will be reported; all subsequent errors will be |
| 815 | * silently ignored. |
| 816 | * |
| 817 | * @param {!(Array.<TYPE>|webdriver.promise.Promise.<!Array.<TYPE>>)} arr The |
| 818 | * array to iterator over, or a promise that will resolve to said array. |
| 819 | * @param {function(this: SELF, TYPE, number, !Array.<TYPE>): ?} fn The |
| 820 | * function to call for each element in the array. This function should |
| 821 | * expect three arguments (the element, the index, and the array itself. |
| 822 | * @param {SELF=} opt_self The object to be used as the value of 'this' within |
| 823 | * {@code fn}. |
| 824 | * @template TYPE, SELF |
| 825 | */ |
| 826 | webdriver.promise.map = function(arr, fn, opt_self) { |
| 827 | return webdriver.promise.when(arr, function(arr) { |
| 828 | var result = goog.array.map(arr, fn, opt_self); |
| 829 | return webdriver.promise.all(result); |
| 830 | }); |
| 831 | }; |
| 832 | |
| 833 | |
| 834 | /** |
| 835 | * Calls a function for each element in an array, and if the function returns |
| 836 | * true adds the element to a new array. |
| 837 | * |
| 838 | * <p>If the return value of the filter function is a promise, this function |
| 839 | * will wait for it to be fulfilled before determining whether to insert the |
| 840 | * element into the new array. |
| 841 | * |
| 842 | * <p>If the filter function throws or returns a rejected promise, the promise |
| 843 | * returned by this function will be rejected with the same reason. Only the |
| 844 | * first failure will be reported; all subsequent errors will be silently |
| 845 | * ignored. |
| 846 | * |
| 847 | * @param {!(Array.<TYPE>|webdriver.promise.Promise.<!Array.<TYPE>>)} arr The |
| 848 | * array to iterator over, or a promise that will resolve to said array. |
| 849 | * @param {function(this: SELF, TYPE, number, !Array.<TYPE>): ( |
| 850 | * boolean|webdriver.promise.Promise.<boolean>)} fn The function |
| 851 | * to call for each element in the array. |
| 852 | * @param {SELF=} opt_self The object to be used as the value of 'this' within |
| 853 | * {@code fn}. |
| 854 | * @template TYPE, SELF |
| 855 | */ |
| 856 | webdriver.promise.filter = function(arr, fn, opt_self) { |
| 857 | return webdriver.promise.when(arr, function(arr) { |
| 858 | var originalValues = goog.array.clone(arr); |
| 859 | return webdriver.promise.map(arr, fn, opt_self).then(function(include) { |
| 860 | return goog.array.filter(originalValues, function(value, index) { |
| 861 | return include[index]; |
| 862 | }); |
| 863 | }); |
| 864 | }); |
| 865 | }; |
| 866 | |
| 867 | |
| 868 | /** |
| 869 | * Returns a promise that will be resolved with the input value in a |
| 870 | * fully-resolved state. If the value is an array, each element will be fully |
| 871 | * resolved. Likewise, if the value is an object, all keys will be fully |
| 872 | * resolved. In both cases, all nested arrays and objects will also be |
| 873 | * fully resolved. All fields are resolved in place; the returned promise will |
| 874 | * resolve on {@code value} and not a copy. |
| 875 | * |
| 876 | * Warning: This function makes no checks against objects that contain |
| 877 | * cyclical references: |
| 878 | * <pre><code> |
| 879 | * var value = {}; |
| 880 | * value['self'] = value; |
| 881 | * webdriver.promise.fullyResolved(value); // Stack overflow. |
| 882 | * </code></pre> |
| 883 | * |
| 884 | * @param {*} value The value to fully resolve. |
| 885 | * @return {!webdriver.promise.Promise} A promise for a fully resolved version |
| 886 | * of the input value. |
| 887 | */ |
| 888 | webdriver.promise.fullyResolved = function(value) { |
| 889 | if (webdriver.promise.isPromise(value)) { |
| 890 | return webdriver.promise.when(value, webdriver.promise.fullyResolveValue_); |
| 891 | } |
| 892 | return webdriver.promise.fullyResolveValue_(value); |
| 893 | }; |
| 894 | |
| 895 | |
| 896 | /** |
| 897 | * @param {*} value The value to fully resolve. If a promise, assumed to |
| 898 | * already be resolved. |
| 899 | * @return {!webdriver.promise.Promise} A promise for a fully resolved version |
| 900 | * of the input value. |
| 901 | * @private |
| 902 | */ |
| 903 | webdriver.promise.fullyResolveValue_ = function(value) { |
| 904 | switch (goog.typeOf(value)) { |
| 905 | case 'array': |
| 906 | return webdriver.promise.fullyResolveKeys_( |
| 907 | /** @type {!Array} */ (value)); |
| 908 | |
| 909 | case 'object': |
| 910 | if (webdriver.promise.isPromise(value)) { |
| 911 | // We get here when the original input value is a promise that |
| 912 | // resolves to itself. When the user provides us with such a promise, |
| 913 | // trust that it counts as a "fully resolved" value and return it. |
| 914 | // Of course, since it's already a promise, we can just return it |
| 915 | // to the user instead of wrapping it in another promise. |
| 916 | return /** @type {!webdriver.promise.Promise} */ (value); |
| 917 | } |
| 918 | |
| 919 | if (goog.isNumber(value.nodeType) && |
| 920 | goog.isObject(value.ownerDocument) && |
| 921 | goog.isNumber(value.ownerDocument.nodeType)) { |
| 922 | // DOM node; return early to avoid infinite recursion. Should we |
| 923 | // only support objects with a certain level of nesting? |
| 924 | return webdriver.promise.fulfilled(value); |
| 925 | } |
| 926 | |
| 927 | return webdriver.promise.fullyResolveKeys_( |
| 928 | /** @type {!Object} */ (value)); |
| 929 | |
| 930 | default: // boolean, function, null, number, string, undefined |
| 931 | return webdriver.promise.fulfilled(value); |
| 932 | } |
| 933 | }; |
| 934 | |
| 935 | |
| 936 | /** |
| 937 | * @param {!(Array|Object)} obj the object to resolve. |
| 938 | * @return {!webdriver.promise.Promise} A promise that will be resolved with the |
| 939 | * input object once all of its values have been fully resolved. |
| 940 | * @private |
| 941 | */ |
| 942 | webdriver.promise.fullyResolveKeys_ = function(obj) { |
| 943 | var isArray = goog.isArray(obj); |
| 944 | var numKeys = isArray ? obj.length : goog.object.getCount(obj); |
| 945 | if (!numKeys) { |
| 946 | return webdriver.promise.fulfilled(obj); |
| 947 | } |
| 948 | |
| 949 | var numResolved = 0; |
| 950 | var deferred = new webdriver.promise.Deferred(); |
| 951 | |
| 952 | // In pre-IE9, goog.array.forEach will not iterate properly over arrays |
| 953 | // containing undefined values because "index in array" returns false |
| 954 | // when array[index] === undefined (even for x = [undefined, 1]). To get |
| 955 | // around this, we need to use our own forEach implementation. |
| 956 | // DO NOT REMOVE THIS UNTIL WE NO LONGER SUPPORT IE8. This cannot be |
| 957 | // reproduced in IE9 by changing the browser/document modes, it requires an |
| 958 | // actual pre-IE9 browser. Yay, IE! |
| 959 | var forEachKey = !isArray ? goog.object.forEach : function(arr, fn) { |
| 960 | var n = arr.length; |
| 961 | for (var i = 0; i < n; ++i) { |
| 962 | fn.call(null, arr[i], i, arr); |
| 963 | } |
| 964 | }; |
| 965 | |
| 966 | forEachKey(obj, function(partialValue, key) { |
| 967 | var type = goog.typeOf(partialValue); |
| 968 | if (type != 'array' && type != 'object') { |
| 969 | maybeResolveValue(); |
| 970 | return; |
| 971 | } |
| 972 | |
| 973 | webdriver.promise.fullyResolved(partialValue).then( |
| 974 | function(resolvedValue) { |
| 975 | obj[key] = resolvedValue; |
| 976 | maybeResolveValue(); |
| 977 | }, |
| 978 | deferred.reject); |
| 979 | }); |
| 980 | |
| 981 | return deferred.promise; |
| 982 | |
| 983 | function maybeResolveValue() { |
| 984 | if (++numResolved == numKeys) { |
| 985 | deferred.fulfill(obj); |
| 986 | } |
| 987 | } |
| 988 | }; |
| 989 | |
| 990 | |
| 991 | ////////////////////////////////////////////////////////////////////////////// |
| 992 | // |
| 993 | // webdriver.promise.ControlFlow |
| 994 | // |
| 995 | ////////////////////////////////////////////////////////////////////////////// |
| 996 | |
| 997 | |
| 998 | |
| 999 | /** |
| 1000 | * Handles the execution of scheduled tasks, each of which may be an |
| 1001 | * asynchronous operation. The control flow will ensure tasks are executed in |
| 1002 | * the ordered scheduled, starting each task only once those before it have |
| 1003 | * completed. |
| 1004 | * |
| 1005 | * <p>Each task scheduled within this flow may return a |
| 1006 | * {@link webdriver.promise.Promise} to indicate it is an asynchronous |
| 1007 | * operation. The ControlFlow will wait for such promises to be resolved before |
| 1008 | * marking the task as completed. |
| 1009 | * |
| 1010 | * <p>Tasks and each callback registered on a {@link webdriver.promise.Deferred} |
| 1011 | * will be run in their own ControlFlow frame. Any tasks scheduled within a |
| 1012 | * frame will have priority over previously scheduled tasks. Furthermore, if |
| 1013 | * any of the tasks in the frame fails, the remainder of the tasks in that frame |
| 1014 | * will be discarded and the failure will be propagated to the user through the |
| 1015 | * callback/task's promised result. |
| 1016 | * |
| 1017 | * <p>Each time a ControlFlow empties its task queue, it will fire an |
| 1018 | * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Conversely, |
| 1019 | * whenever the flow terminates due to an unhandled error, it will remove all |
| 1020 | * remaining tasks in its queue and fire an |
| 1021 | * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION} event. If |
| 1022 | * there are no listeners registered with the flow, the error will be |
| 1023 | * rethrown to the global error handler. |
| 1024 | * |
| 1025 | * @param {webdriver.promise.ControlFlow.Timer=} opt_timer The timer object |
| 1026 | * to use. Should only be set for testing. |
| 1027 | * @constructor |
| 1028 | * @extends {webdriver.EventEmitter} |
| 1029 | */ |
| 1030 | webdriver.promise.ControlFlow = function(opt_timer) { |
| 1031 | webdriver.EventEmitter.call(this); |
| 1032 | |
| 1033 | /** |
| 1034 | * The timer used by this instance. |
| 1035 | * @type {webdriver.promise.ControlFlow.Timer} |
| 1036 | */ |
| 1037 | this.timer = opt_timer || webdriver.promise.ControlFlow.defaultTimer; |
| 1038 | |
| 1039 | /** |
| 1040 | * A list of recent tasks. Each time a new task is started, or a frame is |
| 1041 | * completed, the previously recorded task is removed from this list. If |
| 1042 | * there are multiple tasks, task N+1 is considered a sub-task of task |
| 1043 | * N. |
| 1044 | * @private {!Array.<!webdriver.promise.Task_>} |
| 1045 | */ |
| 1046 | this.history_ = []; |
| 1047 | }; |
| 1048 | goog.inherits(webdriver.promise.ControlFlow, webdriver.EventEmitter); |
| 1049 | |
| 1050 | |
| 1051 | /** |
| 1052 | * @typedef {{clearInterval: function(number), |
| 1053 | * clearTimeout: function(number), |
| 1054 | * setInterval: function(!Function, number): number, |
| 1055 | * setTimeout: function(!Function, number): number}} |
| 1056 | */ |
| 1057 | webdriver.promise.ControlFlow.Timer; |
| 1058 | |
| 1059 | |
| 1060 | /** |
| 1061 | * The default timer object, which uses the global timer functions. |
| 1062 | * @type {webdriver.promise.ControlFlow.Timer} |
| 1063 | */ |
| 1064 | webdriver.promise.ControlFlow.defaultTimer = (function() { |
| 1065 | // The default timer functions may be defined as free variables for the |
| 1066 | // current context, so do not reference them using "window" or |
| 1067 | // "goog.global". Also, we must invoke them in a closure, and not using |
| 1068 | // bind(), so we do not get "TypeError: Illegal invocation" (WebKit) or |
| 1069 | // "Invalid calling object" (IE) errors. |
| 1070 | return { |
| 1071 | clearInterval: wrap(clearInterval), |
| 1072 | clearTimeout: wrap(clearTimeout), |
| 1073 | setInterval: wrap(setInterval), |
| 1074 | setTimeout: wrap(setTimeout) |
| 1075 | }; |
| 1076 | |
| 1077 | function wrap(fn) { |
| 1078 | return function() { |
| 1079 | // Cannot use .call() or .apply() since we do not know which variable |
| 1080 | // the function is bound to, and using the wrong one will generate |
| 1081 | // an error. |
| 1082 | return fn(arguments[0], arguments[1]); |
| 1083 | }; |
| 1084 | } |
| 1085 | })(); |
| 1086 | |
| 1087 | |
| 1088 | /** |
| 1089 | * Events that may be emitted by an {@link webdriver.promise.ControlFlow}. |
| 1090 | * @enum {string} |
| 1091 | */ |
| 1092 | webdriver.promise.ControlFlow.EventType = { |
| 1093 | |
| 1094 | /** Emitted when all tasks have been successfully executed. */ |
| 1095 | IDLE: 'idle', |
| 1096 | |
| 1097 | /** Emitted when a ControlFlow has been reset. */ |
| 1098 | RESET: 'reset', |
| 1099 | |
| 1100 | /** Emitted whenever a new task has been scheduled. */ |
| 1101 | SCHEDULE_TASK: 'scheduleTask', |
| 1102 | |
| 1103 | /** |
| 1104 | * Emitted whenever a control flow aborts due to an unhandled promise |
| 1105 | * rejection. This event will be emitted along with the offending rejection |
| 1106 | * reason. Upon emitting this event, the control flow will empty its task |
| 1107 | * queue and revert to its initial state. |
| 1108 | */ |
| 1109 | UNCAUGHT_EXCEPTION: 'uncaughtException' |
| 1110 | }; |
| 1111 | |
| 1112 | |
| 1113 | /** |
| 1114 | * How often, in milliseconds, the event loop should run. |
| 1115 | * @type {number} |
| 1116 | * @const |
| 1117 | */ |
| 1118 | webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY = 10; |
| 1119 | |
| 1120 | |
| 1121 | /** |
| 1122 | * Tracks the active execution frame for this instance. Lazily initialized |
| 1123 | * when the first task is scheduled. |
| 1124 | * @private {webdriver.promise.Frame_} |
| 1125 | */ |
| 1126 | webdriver.promise.ControlFlow.prototype.activeFrame_ = null; |
| 1127 | |
| 1128 | |
| 1129 | /** |
| 1130 | * A reference to the frame in which new tasks should be scheduled. If |
| 1131 | * {@code null}, tasks will be scheduled within the active frame. When forcing |
| 1132 | * a function to run in the context of a new frame, this pointer is used to |
| 1133 | * ensure tasks are scheduled within the newly created frame, even though it |
| 1134 | * won't be active yet. |
| 1135 | * @private {webdriver.promise.Frame_} |
| 1136 | * @see {#runInNewFrame_} |
| 1137 | */ |
| 1138 | webdriver.promise.ControlFlow.prototype.schedulingFrame_ = null; |
| 1139 | |
| 1140 | |
| 1141 | /** |
| 1142 | * Timeout ID set when the flow is about to shutdown without any errors |
| 1143 | * being detected. Upon shutting down, the flow will emit an |
| 1144 | * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Idle events |
| 1145 | * always follow a brief timeout in order to catch latent errors from the last |
| 1146 | * completed task. If this task had a callback registered, but no errback, and |
| 1147 | * the task fails, the unhandled failure would not be reported by the promise |
| 1148 | * system until the next turn of the event loop: |
| 1149 | * |
| 1150 | * // Schedule 1 task that fails. |
| 1151 | * var result = webriver.promise.controlFlow().schedule('example', |
| 1152 | * function() { return webdriver.promise.rejected('failed'); }); |
| 1153 | * // Set a callback on the result. This delays reporting the unhandled |
| 1154 | * // failure for 1 turn of the event loop. |
| 1155 | * result.then(goog.nullFunction); |
| 1156 | * |
| 1157 | * @private {?number} |
| 1158 | */ |
| 1159 | webdriver.promise.ControlFlow.prototype.shutdownId_ = null; |
| 1160 | |
| 1161 | |
| 1162 | /** |
| 1163 | * Interval ID for this instance's event loop. |
| 1164 | * @private {?number} |
| 1165 | */ |
| 1166 | webdriver.promise.ControlFlow.prototype.eventLoopId_ = null; |
| 1167 | |
| 1168 | |
| 1169 | /** |
| 1170 | * The number of "pending" promise rejections. |
| 1171 | * |
| 1172 | * <p>Each time a promise is rejected and is not handled by a listener, it will |
| 1173 | * schedule a 0-based timeout to check if it is still unrejected in the next |
| 1174 | * turn of the JS-event loop. This allows listeners to attach to, and handle, |
| 1175 | * the rejected promise at any point in same turn of the event loop that the |
| 1176 | * promise was rejected. |
| 1177 | * |
| 1178 | * <p>When this flow's own event loop triggers, it will not run if there |
| 1179 | * are any outstanding promise rejections. This allows unhandled promises to |
| 1180 | * be reported before a new task is started, ensuring the error is reported to |
| 1181 | * the current task queue. |
| 1182 | * |
| 1183 | * @private {number} |
| 1184 | */ |
| 1185 | webdriver.promise.ControlFlow.prototype.pendingRejections_ = 0; |
| 1186 | |
| 1187 | |
| 1188 | /** |
| 1189 | * The number of aborted frames since the last time a task was executed or a |
| 1190 | * frame completed successfully. |
| 1191 | * @private {number} |
| 1192 | */ |
| 1193 | webdriver.promise.ControlFlow.prototype.numAbortedFrames_ = 0; |
| 1194 | |
| 1195 | |
| 1196 | /** |
| 1197 | * Resets this instance, clearing its queue and removing all event listeners. |
| 1198 | */ |
| 1199 | webdriver.promise.ControlFlow.prototype.reset = function() { |
| 1200 | this.activeFrame_ = null; |
| 1201 | this.clearHistory(); |
| 1202 | this.emit(webdriver.promise.ControlFlow.EventType.RESET); |
| 1203 | this.removeAllListeners(); |
| 1204 | this.cancelShutdown_(); |
| 1205 | this.cancelEventLoop_(); |
| 1206 | }; |
| 1207 | |
| 1208 | |
| 1209 | /** |
| 1210 | * Returns a summary of the recent task activity for this instance. This |
| 1211 | * includes the most recently completed task, as well as any parent tasks. In |
| 1212 | * the returned summary, the task at index N is considered a sub-task of the |
| 1213 | * task at index N+1. |
| 1214 | * @return {!Array.<string>} A summary of this instance's recent task |
| 1215 | * activity. |
| 1216 | */ |
| 1217 | webdriver.promise.ControlFlow.prototype.getHistory = function() { |
| 1218 | var pendingTasks = []; |
| 1219 | var currentFrame = this.activeFrame_; |
| 1220 | while (currentFrame) { |
| 1221 | var task = currentFrame.getPendingTask(); |
| 1222 | if (task) { |
| 1223 | pendingTasks.push(task); |
| 1224 | } |
| 1225 | // A frame's parent node will always be another frame. |
| 1226 | currentFrame = |
| 1227 | /** @type {webdriver.promise.Frame_} */ (currentFrame.getParent()); |
| 1228 | } |
| 1229 | |
| 1230 | var fullHistory = goog.array.concat(this.history_, pendingTasks); |
| 1231 | return goog.array.map(fullHistory, function(task) { |
| 1232 | return task.toString(); |
| 1233 | }); |
| 1234 | }; |
| 1235 | |
| 1236 | |
| 1237 | /** Clears this instance's task history. */ |
| 1238 | webdriver.promise.ControlFlow.prototype.clearHistory = function() { |
| 1239 | this.history_ = []; |
| 1240 | }; |
| 1241 | |
| 1242 | |
| 1243 | /** |
| 1244 | * Removes a completed task from this instance's history record. If any |
| 1245 | * tasks remain from aborted frames, those will be removed as well. |
| 1246 | * @private |
| 1247 | */ |
| 1248 | webdriver.promise.ControlFlow.prototype.trimHistory_ = function() { |
| 1249 | if (this.numAbortedFrames_) { |
| 1250 | goog.array.splice(this.history_, |
| 1251 | this.history_.length - this.numAbortedFrames_, |
| 1252 | this.numAbortedFrames_); |
| 1253 | this.numAbortedFrames_ = 0; |
| 1254 | } |
| 1255 | this.history_.pop(); |
| 1256 | }; |
| 1257 | |
| 1258 | |
| 1259 | /** |
| 1260 | * Property used to track whether an error has been annotated by |
| 1261 | * {@link webdriver.promise.ControlFlow#annotateError}. |
| 1262 | * @private {string} |
| 1263 | * @const |
| 1264 | */ |
| 1265 | webdriver.promise.ControlFlow.ANNOTATION_PROPERTY_ = |
| 1266 | 'webdriver_promise_error_'; |
| 1267 | |
| 1268 | |
| 1269 | /** |
| 1270 | * Appends a summary of this instance's recent task history to the given |
| 1271 | * error's stack trace. This function will also ensure the error's stack trace |
| 1272 | * is in canonical form. |
| 1273 | * @param {!(Error|goog.testing.JsUnitException)} e The error to annotate. |
| 1274 | * @return {!(Error|goog.testing.JsUnitException)} The annotated error. |
| 1275 | */ |
| 1276 | webdriver.promise.ControlFlow.prototype.annotateError = function(e) { |
| 1277 | if (!!e[webdriver.promise.ControlFlow.ANNOTATION_PROPERTY_]) { |
| 1278 | return e; |
| 1279 | } |
| 1280 | |
| 1281 | var history = this.getHistory(); |
| 1282 | if (history.length) { |
| 1283 | e = webdriver.stacktrace.format(e); |
| 1284 | |
| 1285 | /** @type {!Error} */(e).stack += [ |
| 1286 | '\n==== async task ====\n', |
| 1287 | history.join('\n==== async task ====\n') |
| 1288 | ].join(''); |
| 1289 | |
| 1290 | e[webdriver.promise.ControlFlow.ANNOTATION_PROPERTY_] = true; |
| 1291 | } |
| 1292 | |
| 1293 | return e; |
| 1294 | }; |
| 1295 | |
| 1296 | |
| 1297 | /** |
| 1298 | * @return {string} The scheduled tasks still pending with this instance. |
| 1299 | */ |
| 1300 | webdriver.promise.ControlFlow.prototype.getSchedule = function() { |
| 1301 | return this.activeFrame_ ? this.activeFrame_.getRoot().toString() : '[]'; |
| 1302 | }; |
| 1303 | |
| 1304 | |
| 1305 | /** |
| 1306 | * Schedules a task for execution. If there is nothing currently in the |
| 1307 | * queue, the task will be executed in the next turn of the event loop. If |
| 1308 | * the task function is a generator, the task will be executed using |
| 1309 | * {@link webdriver.promise.consume}. |
| 1310 | * |
| 1311 | * @param {function(): (T|webdriver.promise.Promise.<T>)} fn The function to |
| 1312 | * call to start the task. If the function returns a |
| 1313 | * {@link webdriver.promise.Promise}, this instance will wait for it to be |
| 1314 | * resolved before starting the next task. |
| 1315 | * @param {string=} opt_description A description of the task. |
| 1316 | * @return {!webdriver.promise.Promise.<T>} A promise that will be resolved |
| 1317 | * with the result of the action. |
| 1318 | * @template T |
| 1319 | */ |
| 1320 | webdriver.promise.ControlFlow.prototype.execute = function( |
| 1321 | fn, opt_description) { |
| 1322 | if (webdriver.promise.isGenerator(fn)) { |
| 1323 | fn = goog.partial(webdriver.promise.consume, fn); |
| 1324 | } |
| 1325 | |
| 1326 | this.cancelShutdown_(); |
| 1327 | |
| 1328 | if (!this.activeFrame_) { |
| 1329 | this.activeFrame_ = new webdriver.promise.Frame_(this); |
| 1330 | } |
| 1331 | |
| 1332 | // Trim an extra frame off the generated stack trace for the call to this |
| 1333 | // function. |
| 1334 | var snapshot = new webdriver.stacktrace.Snapshot(1); |
| 1335 | var task = new webdriver.promise.Task_( |
| 1336 | this, fn, opt_description || '', snapshot); |
| 1337 | var scheduleIn = this.schedulingFrame_ || this.activeFrame_; |
| 1338 | scheduleIn.addChild(task); |
| 1339 | |
| 1340 | this.emit(webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK, opt_description); |
| 1341 | |
| 1342 | this.scheduleEventLoopStart_(); |
| 1343 | return task.promise; |
| 1344 | }; |
| 1345 | |
| 1346 | |
| 1347 | /** |
| 1348 | * Inserts a {@code setTimeout} into the command queue. This is equivalent to |
| 1349 | * a thread sleep in a synchronous programming language. |
| 1350 | * |
| 1351 | * @param {number} ms The timeout delay, in milliseconds. |
| 1352 | * @param {string=} opt_description A description to accompany the timeout. |
| 1353 | * @return {!webdriver.promise.Promise} A promise that will be resolved with |
| 1354 | * the result of the action. |
| 1355 | */ |
| 1356 | webdriver.promise.ControlFlow.prototype.timeout = function( |
| 1357 | ms, opt_description) { |
| 1358 | return this.execute(function() { |
| 1359 | return webdriver.promise.delayed(ms); |
| 1360 | }, opt_description); |
| 1361 | }; |
| 1362 | |
| 1363 | |
| 1364 | /** |
| 1365 | * Schedules a task that shall wait for a condition to hold. Each condition |
| 1366 | * function may return any value, but it will always be evaluated as a boolean. |
| 1367 | * |
| 1368 | * <p>Condition functions may schedule sub-tasks with this instance, however, |
| 1369 | * their execution time will be factored into whether a wait has timed out. |
| 1370 | * |
| 1371 | * <p>In the event a condition returns a Promise, the polling loop will wait for |
| 1372 | * it to be resolved before evaluating whether the condition has been satisfied. |
| 1373 | * The resolution time for a promise is factored into whether a wait has timed |
| 1374 | * out. |
| 1375 | * |
| 1376 | * <p>If the condition function throws, or returns a rejected promise, the |
| 1377 | * wait task will fail. |
| 1378 | * |
| 1379 | * @param {!Function} condition The condition function to poll. |
| 1380 | * @param {number} timeout How long to wait, in milliseconds, for the condition |
| 1381 | * to hold before timing out. |
| 1382 | * @param {string=} opt_message An optional error message to include if the |
| 1383 | * wait times out; defaults to the empty string. |
| 1384 | * @return {!webdriver.promise.Promise} A promise that will be resolved when the |
| 1385 | * condition has been satisified. The promise shall be rejected if the wait |
| 1386 | * times out waiting for the condition. |
| 1387 | */ |
| 1388 | webdriver.promise.ControlFlow.prototype.wait = function( |
| 1389 | condition, timeout, opt_message) { |
| 1390 | var sleep = Math.min(timeout, 100); |
| 1391 | var self = this; |
| 1392 | |
| 1393 | if (webdriver.promise.isGenerator(condition)) { |
| 1394 | condition = goog.partial(webdriver.promise.consume, condition); |
| 1395 | } |
| 1396 | |
| 1397 | return this.execute(function() { |
| 1398 | var startTime = goog.now(); |
| 1399 | var waitResult = new webdriver.promise.Deferred(); |
| 1400 | var waitFrame = self.activeFrame_; |
| 1401 | waitFrame.isWaiting = true; |
| 1402 | pollCondition(); |
| 1403 | return waitResult.promise; |
| 1404 | |
| 1405 | function pollCondition() { |
| 1406 | self.runInNewFrame_(condition, function(value) { |
| 1407 | var elapsed = goog.now() - startTime; |
| 1408 | if (!!value) { |
| 1409 | waitFrame.isWaiting = false; |
| 1410 | waitResult.fulfill(value); |
| 1411 | } else if (elapsed >= timeout) { |
| 1412 | waitResult.reject(new Error((opt_message ? opt_message + '\n' : '') + |
| 1413 | 'Wait timed out after ' + elapsed + 'ms')); |
| 1414 | } else { |
| 1415 | self.timer.setTimeout(pollCondition, sleep); |
| 1416 | } |
| 1417 | }, waitResult.reject, true); |
| 1418 | } |
| 1419 | }, opt_message); |
| 1420 | }; |
| 1421 | |
| 1422 | |
| 1423 | /** |
| 1424 | * Schedules a task that will wait for another promise to resolve. The resolved |
| 1425 | * promise's value will be returned as the task result. |
| 1426 | * @param {!webdriver.promise.Promise} promise The promise to wait on. |
| 1427 | * @return {!webdriver.promise.Promise} A promise that will resolve when the |
| 1428 | * task has completed. |
| 1429 | */ |
| 1430 | webdriver.promise.ControlFlow.prototype.await = function(promise) { |
| 1431 | return this.execute(function() { |
| 1432 | return promise; |
| 1433 | }); |
| 1434 | }; |
| 1435 | |
| 1436 | |
| 1437 | /** |
| 1438 | * Schedules the interval for this instance's event loop, if necessary. |
| 1439 | * @private |
| 1440 | */ |
| 1441 | webdriver.promise.ControlFlow.prototype.scheduleEventLoopStart_ = function() { |
| 1442 | if (!this.eventLoopId_) { |
| 1443 | this.eventLoopId_ = this.timer.setInterval( |
| 1444 | goog.bind(this.runEventLoop_, this), |
| 1445 | webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY); |
| 1446 | } |
| 1447 | }; |
| 1448 | |
| 1449 | |
| 1450 | /** |
| 1451 | * Cancels the event loop, if necessary. |
| 1452 | * @private |
| 1453 | */ |
| 1454 | webdriver.promise.ControlFlow.prototype.cancelEventLoop_ = function() { |
| 1455 | if (this.eventLoopId_) { |
| 1456 | this.timer.clearInterval(this.eventLoopId_); |
| 1457 | this.eventLoopId_ = null; |
| 1458 | } |
| 1459 | }; |
| 1460 | |
| 1461 | |
| 1462 | /** |
| 1463 | * Executes the next task for the current frame. If the current frame has no |
| 1464 | * more tasks, the frame's result will be resolved, returning control to the |
| 1465 | * frame's creator. This will terminate the flow if the completed frame was at |
| 1466 | * the top of the stack. |
| 1467 | * @private |
| 1468 | */ |
| 1469 | webdriver.promise.ControlFlow.prototype.runEventLoop_ = function() { |
| 1470 | // If we get here and there are pending promise rejections, then those |
| 1471 | // promises are queued up to run as soon as this (JS) event loop terminates. |
| 1472 | // Short-circuit our loop to give those promises a chance to run. Otherwise, |
| 1473 | // we might start a new task only to have it fail because of one of these |
| 1474 | // pending rejections. |
| 1475 | if (this.pendingRejections_) { |
| 1476 | return; |
| 1477 | } |
| 1478 | |
| 1479 | // If the flow aborts due to an unhandled exception after we've scheduled |
| 1480 | // another turn of the execution loop, we can end up in here with no tasks |
| 1481 | // left. This is OK, just quietly return. |
| 1482 | if (!this.activeFrame_) { |
| 1483 | this.commenceShutdown_(); |
| 1484 | return; |
| 1485 | } |
| 1486 | |
| 1487 | var task; |
| 1488 | if (this.activeFrame_.getPendingTask() || !(task = this.getNextTask_())) { |
| 1489 | // Either the current frame is blocked on a pending task, or we don't have |
| 1490 | // a task to finish because we've completed a frame. When completing a |
| 1491 | // frame, we must abort the event loop to allow the frame's promise's |
| 1492 | // callbacks to execute. |
| 1493 | return; |
| 1494 | } |
| 1495 | |
| 1496 | var activeFrame = this.activeFrame_; |
| 1497 | activeFrame.setPendingTask(task); |
| 1498 | var markTaskComplete = goog.bind(function() { |
| 1499 | this.history_.push(/** @type {!webdriver.promise.Task_} */ (task)); |
| 1500 | activeFrame.setPendingTask(null); |
| 1501 | }, this); |
| 1502 | |
| 1503 | this.trimHistory_(); |
| 1504 | var self = this; |
| 1505 | this.runInNewFrame_(task.execute, function(result) { |
| 1506 | markTaskComplete(); |
| 1507 | task.fulfill(result); |
| 1508 | }, function(error) { |
| 1509 | markTaskComplete(); |
| 1510 | |
| 1511 | if (!webdriver.promise.isError_(error) && |
| 1512 | !webdriver.promise.isPromise(error)) { |
| 1513 | error = Error(error); |
| 1514 | } |
| 1515 | |
| 1516 | task.reject(self.annotateError(/** @type {!Error} */ (error))); |
| 1517 | }, true); |
| 1518 | }; |
| 1519 | |
| 1520 | |
| 1521 | /** |
| 1522 | * @return {webdriver.promise.Task_} The next task to execute, or |
| 1523 | * {@code null} if a frame was resolved. |
| 1524 | * @private |
| 1525 | */ |
| 1526 | webdriver.promise.ControlFlow.prototype.getNextTask_ = function() { |
| 1527 | var firstChild = this.activeFrame_.getFirstChild(); |
| 1528 | if (!firstChild) { |
| 1529 | if (!this.activeFrame_.isWaiting) { |
| 1530 | this.resolveFrame_(this.activeFrame_); |
| 1531 | } |
| 1532 | return null; |
| 1533 | } |
| 1534 | |
| 1535 | if (firstChild instanceof webdriver.promise.Frame_) { |
| 1536 | this.activeFrame_ = firstChild; |
| 1537 | return this.getNextTask_(); |
| 1538 | } |
| 1539 | |
| 1540 | firstChild.getParent().removeChild(firstChild); |
| 1541 | return firstChild; |
| 1542 | }; |
| 1543 | |
| 1544 | |
| 1545 | /** |
| 1546 | * @param {!webdriver.promise.Frame_} frame The frame to resolve. |
| 1547 | * @private |
| 1548 | */ |
| 1549 | webdriver.promise.ControlFlow.prototype.resolveFrame_ = function(frame) { |
| 1550 | if (this.activeFrame_ === frame) { |
| 1551 | // Frame parent is always another frame, but the compiler is not smart |
| 1552 | // enough to recognize this. |
| 1553 | this.activeFrame_ = |
| 1554 | /** @type {webdriver.promise.Frame_} */ (frame.getParent()); |
| 1555 | } |
| 1556 | |
| 1557 | if (frame.getParent()) { |
| 1558 | frame.getParent().removeChild(frame); |
| 1559 | } |
| 1560 | this.trimHistory_(); |
| 1561 | frame.fulfill(); |
| 1562 | |
| 1563 | if (!this.activeFrame_) { |
| 1564 | this.commenceShutdown_(); |
| 1565 | } |
| 1566 | }; |
| 1567 | |
| 1568 | |
| 1569 | /** |
| 1570 | * Aborts the current frame. The frame, and all of the tasks scheduled within it |
| 1571 | * will be discarded. If this instance does not have an active frame, it will |
| 1572 | * immediately terminate all execution. |
| 1573 | * @param {*} error The reason the frame is being aborted; typically either |
| 1574 | * an Error or string. |
| 1575 | * @private |
| 1576 | */ |
| 1577 | webdriver.promise.ControlFlow.prototype.abortFrame_ = function(error) { |
| 1578 | // Annotate the error value if it is Error-like. |
| 1579 | if (webdriver.promise.isError_(error)) { |
| 1580 | this.annotateError(/** @type {!Error} */ (error)); |
| 1581 | } |
| 1582 | this.numAbortedFrames_++; |
| 1583 | |
| 1584 | if (!this.activeFrame_) { |
| 1585 | this.abortNow_(error); |
| 1586 | return; |
| 1587 | } |
| 1588 | |
| 1589 | // Frame parent is always another frame, but the compiler is not smart |
| 1590 | // enough to recognize this. |
| 1591 | var parent = /** @type {webdriver.promise.Frame_} */ ( |
| 1592 | this.activeFrame_.getParent()); |
| 1593 | if (parent) { |
| 1594 | parent.removeChild(this.activeFrame_); |
| 1595 | } |
| 1596 | |
| 1597 | var frame = this.activeFrame_; |
| 1598 | this.activeFrame_ = parent; |
| 1599 | frame.reject(error); |
| 1600 | }; |
| 1601 | |
| 1602 | |
| 1603 | /** |
| 1604 | * Executes a function in a new frame. If the function does not schedule any new |
| 1605 | * tasks, the frame will be discarded and the function's result returned |
| 1606 | * immediately. Otherwise, a promise will be returned. This promise will be |
| 1607 | * resolved with the function's result once all of the tasks scheduled within |
| 1608 | * the function have been completed. If the function's frame is aborted, the |
| 1609 | * returned promise will be rejected. |
| 1610 | * |
| 1611 | * @param {!Function} fn The function to execute. |
| 1612 | * @param {function(*)} callback The function to call with a successful result. |
| 1613 | * @param {function(*)} errback The function to call if there is an error. |
| 1614 | * @param {boolean=} opt_activate Whether the active frame should be updated to |
| 1615 | * the newly created frame so tasks are treated as sub-tasks. |
| 1616 | * @private |
| 1617 | */ |
| 1618 | webdriver.promise.ControlFlow.prototype.runInNewFrame_ = function( |
| 1619 | fn, callback, errback, opt_activate) { |
| 1620 | var newFrame = new webdriver.promise.Frame_(this), |
| 1621 | self = this, |
| 1622 | oldFrame = this.activeFrame_; |
| 1623 | |
| 1624 | try { |
| 1625 | if (!this.activeFrame_) { |
| 1626 | this.activeFrame_ = newFrame; |
| 1627 | } else { |
| 1628 | this.activeFrame_.addChild(newFrame); |
| 1629 | } |
| 1630 | |
| 1631 | // Activate the new frame to force tasks to be treated as sub-tasks of |
| 1632 | // the parent frame. |
| 1633 | if (opt_activate) { |
| 1634 | this.activeFrame_ = newFrame; |
| 1635 | } |
| 1636 | |
| 1637 | try { |
| 1638 | this.schedulingFrame_ = newFrame; |
| 1639 | webdriver.promise.pushFlow_(this); |
| 1640 | var result = fn(); |
| 1641 | } finally { |
| 1642 | webdriver.promise.popFlow_(); |
| 1643 | this.schedulingFrame_ = null; |
| 1644 | } |
| 1645 | newFrame.lockFrame(); |
| 1646 | |
| 1647 | // If there was nothing scheduled in the new frame we can discard the |
| 1648 | // frame and return immediately. |
| 1649 | if (!newFrame.children_.length) { |
| 1650 | removeNewFrame(); |
| 1651 | webdriver.promise.asap(result, callback, errback); |
| 1652 | return; |
| 1653 | } |
| 1654 | |
| 1655 | newFrame.then(function() { |
| 1656 | webdriver.promise.asap(result, callback, errback); |
| 1657 | }, function(e) { |
| 1658 | if (webdriver.promise.Thenable.isImplementation(result) && |
| 1659 | result.isPending()) { |
| 1660 | result.cancel(e); |
| 1661 | e = result; |
| 1662 | } |
| 1663 | errback(e); |
| 1664 | }); |
| 1665 | } catch (ex) { |
| 1666 | removeNewFrame(new webdriver.promise.CanceledTaskError_(ex)); |
| 1667 | errback(ex); |
| 1668 | } |
| 1669 | |
| 1670 | /** |
| 1671 | * @param {webdriver.promise.CanceledTaskError_=} opt_err If provided, the |
| 1672 | * error that triggered the removal of this frame. |
| 1673 | */ |
| 1674 | function removeNewFrame(opt_err) { |
| 1675 | var parent = newFrame.getParent(); |
| 1676 | if (parent) { |
| 1677 | parent.removeChild(newFrame); |
| 1678 | } |
| 1679 | |
| 1680 | if (opt_err) { |
| 1681 | newFrame.cancelRemainingTasks(opt_err); |
| 1682 | } |
| 1683 | self.activeFrame_ = oldFrame; |
| 1684 | } |
| 1685 | }; |
| 1686 | |
| 1687 | |
| 1688 | /** |
| 1689 | * Commences the shutdown sequence for this instance. After one turn of the |
| 1690 | * event loop, this object will emit the |
| 1691 | * {@link webdriver.promise.ControlFlow.EventType.IDLE} event to signal |
| 1692 | * listeners that it has completed. During this wait, if another task is |
| 1693 | * scheduled, the shutdown will be aborted. |
| 1694 | * @private |
| 1695 | */ |
| 1696 | webdriver.promise.ControlFlow.prototype.commenceShutdown_ = function() { |
| 1697 | if (!this.shutdownId_) { |
| 1698 | // Go ahead and stop the event loop now. If we're in here, then there are |
| 1699 | // no more frames with tasks to execute. If we waited to cancel the event |
| 1700 | // loop in our timeout below, the event loop could trigger *before* the |
| 1701 | // timeout, generating an error from there being no frames. |
| 1702 | // If #execute is called before the timeout below fires, it will cancel |
| 1703 | // the timeout and restart the event loop. |
| 1704 | this.cancelEventLoop_(); |
| 1705 | |
| 1706 | var self = this; |
| 1707 | self.shutdownId_ = self.timer.setTimeout(function() { |
| 1708 | self.shutdownId_ = null; |
| 1709 | self.emit(webdriver.promise.ControlFlow.EventType.IDLE); |
| 1710 | }, 0); |
| 1711 | } |
| 1712 | }; |
| 1713 | |
| 1714 | |
| 1715 | /** |
| 1716 | * Cancels the shutdown sequence if it is currently scheduled. |
| 1717 | * @private |
| 1718 | */ |
| 1719 | webdriver.promise.ControlFlow.prototype.cancelShutdown_ = function() { |
| 1720 | if (this.shutdownId_) { |
| 1721 | this.timer.clearTimeout(this.shutdownId_); |
| 1722 | this.shutdownId_ = null; |
| 1723 | } |
| 1724 | }; |
| 1725 | |
| 1726 | |
| 1727 | /** |
| 1728 | * Aborts this flow, abandoning all remaining tasks. If there are |
| 1729 | * listeners registered, an {@code UNCAUGHT_EXCEPTION} will be emitted with the |
| 1730 | * offending {@code error}, otherwise, the {@code error} will be rethrown to the |
| 1731 | * global error handler. |
| 1732 | * @param {*} error Object describing the error that caused the flow to |
| 1733 | * abort; usually either an Error or string value. |
| 1734 | * @private |
| 1735 | */ |
| 1736 | webdriver.promise.ControlFlow.prototype.abortNow_ = function(error) { |
| 1737 | this.activeFrame_ = null; |
| 1738 | this.cancelShutdown_(); |
| 1739 | this.cancelEventLoop_(); |
| 1740 | |
| 1741 | var listeners = this.listeners( |
| 1742 | webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION); |
| 1743 | if (!listeners.length) { |
| 1744 | this.timer.setTimeout(function() { |
| 1745 | throw error; |
| 1746 | }, 0); |
| 1747 | } else { |
| 1748 | this.emit(webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION, |
| 1749 | error); |
| 1750 | } |
| 1751 | }; |
| 1752 | |
| 1753 | |
| 1754 | |
| 1755 | /** |
| 1756 | * A single node in an {@link webdriver.promise.ControlFlow}'s task tree. |
| 1757 | * @param {!webdriver.promise.ControlFlow} flow The flow this instance belongs |
| 1758 | * to. |
| 1759 | * @constructor |
| 1760 | * @extends {webdriver.promise.Deferred} |
| 1761 | * @private |
| 1762 | */ |
| 1763 | webdriver.promise.Node_ = function(flow) { |
| 1764 | webdriver.promise.Deferred.call(this, null, flow); |
| 1765 | }; |
| 1766 | goog.inherits(webdriver.promise.Node_, webdriver.promise.Deferred); |
| 1767 | |
| 1768 | |
| 1769 | /** |
| 1770 | * This node's parent. |
| 1771 | * @private {webdriver.promise.Node_} |
| 1772 | */ |
| 1773 | webdriver.promise.Node_.prototype.parent_ = null; |
| 1774 | |
| 1775 | |
| 1776 | /** @return {webdriver.promise.Node_} This node's parent. */ |
| 1777 | webdriver.promise.Node_.prototype.getParent = function() { |
| 1778 | return this.parent_; |
| 1779 | }; |
| 1780 | |
| 1781 | |
| 1782 | /** |
| 1783 | * @param {webdriver.promise.Node_} parent This node's new parent. |
| 1784 | */ |
| 1785 | webdriver.promise.Node_.prototype.setParent = function(parent) { |
| 1786 | this.parent_ = parent; |
| 1787 | }; |
| 1788 | |
| 1789 | |
| 1790 | /** |
| 1791 | * @return {!webdriver.promise.Node_} The root of this node's tree. |
| 1792 | */ |
| 1793 | webdriver.promise.Node_.prototype.getRoot = function() { |
| 1794 | var root = this; |
| 1795 | while (root.parent_) { |
| 1796 | root = root.parent_; |
| 1797 | } |
| 1798 | return root; |
| 1799 | }; |
| 1800 | |
| 1801 | |
| 1802 | |
| 1803 | /** |
| 1804 | * An execution frame within a {@link webdriver.promise.ControlFlow}. Each |
| 1805 | * frame represents the execution context for either a |
| 1806 | * {@link webdriver.promise.Task_} or a callback on a |
| 1807 | * {@link webdriver.promise.Deferred}. |
| 1808 | * |
| 1809 | * <p>Each frame may contain sub-frames. If child N is a sub-frame, then the |
| 1810 | * items queued within it are given priority over child N+1. |
| 1811 | * |
| 1812 | * @param {!webdriver.promise.ControlFlow} flow The flow this instance belongs |
| 1813 | * to. |
| 1814 | * @constructor |
| 1815 | * @extends {webdriver.promise.Node_} |
| 1816 | * @private |
| 1817 | */ |
| 1818 | webdriver.promise.Frame_ = function(flow) { |
| 1819 | webdriver.promise.Node_.call(this, flow); |
| 1820 | |
| 1821 | var reject = goog.bind(this.reject, this); |
| 1822 | var cancelRemainingTasks = goog.bind(this.cancelRemainingTasks, this); |
| 1823 | |
| 1824 | /** @override */ |
| 1825 | this.reject = function(e) { |
| 1826 | cancelRemainingTasks(new webdriver.promise.CanceledTaskError_(e)); |
| 1827 | reject(e); |
| 1828 | }; |
| 1829 | |
| 1830 | /** |
| 1831 | * @private {!Array.<!(webdriver.promise.Frame_|webdriver.promise.Task_)>} |
| 1832 | */ |
| 1833 | this.children_ = []; |
| 1834 | }; |
| 1835 | goog.inherits(webdriver.promise.Frame_, webdriver.promise.Node_); |
| 1836 | |
| 1837 | |
| 1838 | /** |
| 1839 | * The task currently being executed within this frame. |
| 1840 | * @private {webdriver.promise.Task_} |
| 1841 | */ |
| 1842 | webdriver.promise.Frame_.prototype.pendingTask_ = null; |
| 1843 | |
| 1844 | |
| 1845 | /** |
| 1846 | * Whether this frame is active. A frame is considered active once one of its |
| 1847 | * descendants has been removed for execution. |
| 1848 | * |
| 1849 | * Adding a sub-frame as a child to an active frame is an indication that |
| 1850 | * a callback to a {@link webdriver.promise.Deferred} is being invoked and any |
| 1851 | * tasks scheduled within it should have priority over previously scheduled |
| 1852 | * tasks: |
| 1853 | * <code><pre> |
| 1854 | * var flow = webdriver.promise.controlFlow(); |
| 1855 | * flow.execute('start here', goog.nullFunction).then(function() { |
| 1856 | * flow.execute('this should execute 2nd', goog.nullFunction); |
| 1857 | * }); |
| 1858 | * flow.execute('this should execute last', goog.nullFunction); |
| 1859 | * </pre></code> |
| 1860 | * |
| 1861 | * @private {boolean} |
| 1862 | */ |
| 1863 | webdriver.promise.Frame_.prototype.isActive_ = false; |
| 1864 | |
| 1865 | |
| 1866 | /** |
| 1867 | * Whether this frame is currently locked. A locked frame represents a callback |
| 1868 | * or task function which has run to completion and scheduled all of its tasks. |
| 1869 | * |
| 1870 | * <p>Once a frame becomes {@link #isActive_ active}, any new frames which are |
| 1871 | * added represent callbacks on a {@link webdriver.promise.Deferred}, whose |
| 1872 | * tasks must be given priority over previously scheduled tasks. |
| 1873 | * |
| 1874 | * @private {boolean} |
| 1875 | */ |
| 1876 | webdriver.promise.Frame_.prototype.isLocked_ = false; |
| 1877 | |
| 1878 | |
| 1879 | /** |
| 1880 | * A reference to the last node inserted in this frame. |
| 1881 | * @private {webdriver.promise.Node_} |
| 1882 | */ |
| 1883 | webdriver.promise.Frame_.prototype.lastInsertedChild_ = null; |
| 1884 | |
| 1885 | |
| 1886 | /** |
| 1887 | * Marks all of the tasks that are descendants of this frame in the execution |
| 1888 | * tree as cancelled. This is necessary for callbacks scheduled asynchronous. |
| 1889 | * For example: |
| 1890 | * |
| 1891 | * var someResult; |
| 1892 | * webdriver.promise.createFlow(function(flow) { |
| 1893 | * someResult = flow.execute(function() {}); |
| 1894 | * throw Error(); |
| 1895 | * }).addErrback(function(err) { |
| 1896 | * console.log('flow failed: ' + err); |
| 1897 | * someResult.then(function() { |
| 1898 | * console.log('task succeeded!'); |
| 1899 | * }, function(err) { |
| 1900 | * console.log('task failed! ' + err); |
| 1901 | * }); |
| 1902 | * }); |
| 1903 | * // flow failed: Error: boom |
| 1904 | * // task failed! CanceledTaskError: Task discarded due to a previous |
| 1905 | * // task failure: Error: boom |
| 1906 | * |
| 1907 | * @param {!webdriver.promise.CanceledTaskError_} error The cancellation |
| 1908 | * error. |
| 1909 | */ |
| 1910 | webdriver.promise.Frame_.prototype.cancelRemainingTasks = function(error) { |
| 1911 | goog.array.forEach(this.children_, function(child) { |
| 1912 | if (child instanceof webdriver.promise.Frame_) { |
| 1913 | child.cancelRemainingTasks(error); |
| 1914 | } else { |
| 1915 | // None of the previously registered listeners should be notified that |
| 1916 | // the task is being canceled, however, we need at least one errback |
| 1917 | // to prevent the cancellation from bubbling up. |
| 1918 | child.removeAll(); |
| 1919 | child.thenCatch(goog.nullFunction); |
| 1920 | child.cancel(error); |
| 1921 | } |
| 1922 | }); |
| 1923 | }; |
| 1924 | |
| 1925 | |
| 1926 | /** |
| 1927 | * @return {webdriver.promise.Task_} The task currently executing |
| 1928 | * within this frame, if any. |
| 1929 | */ |
| 1930 | webdriver.promise.Frame_.prototype.getPendingTask = function() { |
| 1931 | return this.pendingTask_; |
| 1932 | }; |
| 1933 | |
| 1934 | |
| 1935 | /** |
| 1936 | * @param {webdriver.promise.Task_} task The task currently |
| 1937 | * executing within this frame, if any. |
| 1938 | */ |
| 1939 | webdriver.promise.Frame_.prototype.setPendingTask = function(task) { |
| 1940 | this.pendingTask_ = task; |
| 1941 | }; |
| 1942 | |
| 1943 | |
| 1944 | /** Locks this frame. */ |
| 1945 | webdriver.promise.Frame_.prototype.lockFrame = function() { |
| 1946 | this.isLocked_ = true; |
| 1947 | }; |
| 1948 | |
| 1949 | |
| 1950 | /** |
| 1951 | * Adds a new node to this frame. |
| 1952 | * @param {!(webdriver.promise.Frame_|webdriver.promise.Task_)} node |
| 1953 | * The node to insert. |
| 1954 | */ |
| 1955 | webdriver.promise.Frame_.prototype.addChild = function(node) { |
| 1956 | if (this.lastInsertedChild_ && |
| 1957 | this.lastInsertedChild_ instanceof webdriver.promise.Frame_ && |
| 1958 | !this.lastInsertedChild_.isLocked_) { |
| 1959 | this.lastInsertedChild_.addChild(node); |
| 1960 | return; |
| 1961 | } |
| 1962 | |
| 1963 | node.setParent(this); |
| 1964 | |
| 1965 | if (this.isActive_ && node instanceof webdriver.promise.Frame_) { |
| 1966 | var index = 0; |
| 1967 | if (this.lastInsertedChild_ instanceof |
| 1968 | webdriver.promise.Frame_) { |
| 1969 | index = goog.array.indexOf(this.children_, this.lastInsertedChild_) + 1; |
| 1970 | } |
| 1971 | goog.array.insertAt(this.children_, node, index); |
| 1972 | this.lastInsertedChild_ = node; |
| 1973 | return; |
| 1974 | } |
| 1975 | |
| 1976 | this.lastInsertedChild_ = node; |
| 1977 | this.children_.push(node); |
| 1978 | }; |
| 1979 | |
| 1980 | |
| 1981 | /** |
| 1982 | * @return {(webdriver.promise.Frame_|webdriver.promise.Task_)} This frame's |
| 1983 | * fist child. |
| 1984 | */ |
| 1985 | webdriver.promise.Frame_.prototype.getFirstChild = function() { |
| 1986 | this.isActive_ = true; |
| 1987 | this.lastInsertedChild_ = null; |
| 1988 | return this.children_[0]; |
| 1989 | }; |
| 1990 | |
| 1991 | |
| 1992 | /** |
| 1993 | * Removes a child from this frame. |
| 1994 | * @param {!(webdriver.promise.Frame_|webdriver.promise.Task_)} child |
| 1995 | * The child to remove. |
| 1996 | */ |
| 1997 | webdriver.promise.Frame_.prototype.removeChild = function(child) { |
| 1998 | var index = goog.array.indexOf(this.children_, child); |
| 1999 | child.setParent(null); |
| 2000 | goog.array.removeAt(this.children_, index); |
| 2001 | if (this.lastInsertedChild_ === child) { |
| 2002 | this.lastInsertedChild_ = null; |
| 2003 | } |
| 2004 | }; |
| 2005 | |
| 2006 | |
| 2007 | /** @override */ |
| 2008 | webdriver.promise.Frame_.prototype.toString = function() { |
| 2009 | return '[' + goog.array.map(this.children_, function(child) { |
| 2010 | return child.toString(); |
| 2011 | }).join(', ') + ']'; |
| 2012 | }; |
| 2013 | |
| 2014 | |
| 2015 | |
| 2016 | /** |
| 2017 | * A task to be executed by a {@link webdriver.promise.ControlFlow}. |
| 2018 | * |
| 2019 | * @param {!webdriver.promise.ControlFlow} flow The flow this instances belongs |
| 2020 | * to. |
| 2021 | * @param {!Function} fn The function to call when the task executes. If it |
| 2022 | * returns a {@code webdriver.promise.Promise}, the flow will wait |
| 2023 | * for it to be resolved before starting the next task. |
| 2024 | * @param {string} description A description of the task for debugging. |
| 2025 | * @param {!webdriver.stacktrace.Snapshot} snapshot A snapshot of the stack |
| 2026 | * when this task was scheduled. |
| 2027 | * @constructor |
| 2028 | * @extends {webdriver.promise.Node_} |
| 2029 | * @private |
| 2030 | */ |
| 2031 | webdriver.promise.Task_ = function(flow, fn, description, snapshot) { |
| 2032 | webdriver.promise.Node_.call(this, flow); |
| 2033 | |
| 2034 | /** |
| 2035 | * Executes this task. |
| 2036 | * @type {!Function} |
| 2037 | */ |
| 2038 | this.execute = fn; |
| 2039 | |
| 2040 | /** @private {string} */ |
| 2041 | this.description_ = description; |
| 2042 | |
| 2043 | /** @private {!webdriver.stacktrace.Snapshot} */ |
| 2044 | this.snapshot_ = snapshot; |
| 2045 | }; |
| 2046 | goog.inherits(webdriver.promise.Task_, webdriver.promise.Node_); |
| 2047 | |
| 2048 | |
| 2049 | /** @return {string} This task's description. */ |
| 2050 | webdriver.promise.Task_.prototype.getDescription = function() { |
| 2051 | return this.description_; |
| 2052 | }; |
| 2053 | |
| 2054 | |
| 2055 | /** @override */ |
| 2056 | webdriver.promise.Task_.prototype.toString = function() { |
| 2057 | var stack = this.snapshot_.getStacktrace(); |
| 2058 | var ret = this.description_; |
| 2059 | if (stack.length) { |
| 2060 | if (this.description_) { |
| 2061 | ret += '\n'; |
| 2062 | } |
| 2063 | ret += stack.join('\n'); |
| 2064 | } |
| 2065 | return ret; |
| 2066 | }; |
| 2067 | |
| 2068 | |
| 2069 | |
| 2070 | /** |
| 2071 | * Special error used to signal when a task is canceled because a previous |
| 2072 | * task in the same frame failed. |
| 2073 | * @param {*} err The error that caused the task cancellation. |
| 2074 | * @constructor |
| 2075 | * @extends {goog.debug.Error} |
| 2076 | * @private |
| 2077 | */ |
| 2078 | webdriver.promise.CanceledTaskError_ = function(err) { |
| 2079 | goog.base(this, 'Task discarded due to a previous task failure: ' + err); |
| 2080 | }; |
| 2081 | goog.inherits(webdriver.promise.CanceledTaskError_, goog.debug.Error); |
| 2082 | |
| 2083 | |
| 2084 | /** @override */ |
| 2085 | webdriver.promise.CanceledTaskError_.prototype.name = 'CanceledTaskError'; |
| 2086 | |
| 2087 | |
| 2088 | |
| 2089 | /** |
| 2090 | * The default flow to use if no others are active. |
| 2091 | * @private {!webdriver.promise.ControlFlow} |
| 2092 | */ |
| 2093 | webdriver.promise.defaultFlow_ = new webdriver.promise.ControlFlow(); |
| 2094 | |
| 2095 | |
| 2096 | /** |
| 2097 | * A stack of active control flows, with the top of the stack used to schedule |
| 2098 | * commands. When there are multiple flows on the stack, the flow at index N |
| 2099 | * represents a callback triggered within a task owned by the flow at index |
| 2100 | * N-1. |
| 2101 | * @private {!Array.<!webdriver.promise.ControlFlow>} |
| 2102 | */ |
| 2103 | webdriver.promise.activeFlows_ = []; |
| 2104 | |
| 2105 | |
| 2106 | /** |
| 2107 | * Changes the default flow to use when no others are active. |
| 2108 | * @param {!webdriver.promise.ControlFlow} flow The new default flow. |
| 2109 | * @throws {Error} If the default flow is not currently active. |
| 2110 | */ |
| 2111 | webdriver.promise.setDefaultFlow = function(flow) { |
| 2112 | if (webdriver.promise.activeFlows_.length) { |
| 2113 | throw Error('You may only change the default flow while it is active'); |
| 2114 | } |
| 2115 | webdriver.promise.defaultFlow_ = flow; |
| 2116 | }; |
| 2117 | |
| 2118 | |
| 2119 | /** |
| 2120 | * @return {!webdriver.promise.ControlFlow} The currently active control flow. |
| 2121 | */ |
| 2122 | webdriver.promise.controlFlow = function() { |
| 2123 | return /** @type {!webdriver.promise.ControlFlow} */ ( |
| 2124 | goog.array.peek(webdriver.promise.activeFlows_) || |
| 2125 | webdriver.promise.defaultFlow_); |
| 2126 | }; |
| 2127 | |
| 2128 | |
| 2129 | /** |
| 2130 | * @param {!webdriver.promise.ControlFlow} flow The new flow. |
| 2131 | * @private |
| 2132 | */ |
| 2133 | webdriver.promise.pushFlow_ = function(flow) { |
| 2134 | webdriver.promise.activeFlows_.push(flow); |
| 2135 | }; |
| 2136 | |
| 2137 | |
| 2138 | /** @private */ |
| 2139 | webdriver.promise.popFlow_ = function() { |
| 2140 | webdriver.promise.activeFlows_.pop(); |
| 2141 | }; |
| 2142 | |
| 2143 | |
| 2144 | /** |
| 2145 | * Creates a new control flow. The provided callback will be invoked as the |
| 2146 | * first task within the new flow, with the flow as its sole argument. Returns |
| 2147 | * a promise that resolves to the callback result. |
| 2148 | * @param {function(!webdriver.promise.ControlFlow)} callback The entry point |
| 2149 | * to the newly created flow. |
| 2150 | * @return {!webdriver.promise.Promise} A promise that resolves to the callback |
| 2151 | * result. |
| 2152 | */ |
| 2153 | webdriver.promise.createFlow = function(callback) { |
| 2154 | var flow = new webdriver.promise.ControlFlow( |
| 2155 | webdriver.promise.defaultFlow_.timer); |
| 2156 | return flow.execute(function() { |
| 2157 | return callback(flow); |
| 2158 | }); |
| 2159 | }; |
| 2160 | |
| 2161 | |
| 2162 | /** |
| 2163 | * Tests is a function is a generator. |
| 2164 | * @param {!Function} fn The function to test. |
| 2165 | * @return {boolean} Whether the function is a generator. |
| 2166 | */ |
| 2167 | webdriver.promise.isGenerator = function(fn) { |
| 2168 | return fn.constructor.name === 'GeneratorFunction'; |
| 2169 | }; |
| 2170 | |
| 2171 | |
| 2172 | /** |
| 2173 | * Consumes a {@code GeneratorFunction}. Each time the generator yields a |
| 2174 | * promise, this function will wait for it to be fulfilled before feeding the |
| 2175 | * fulfilled value back into {@code next}. Likewise, if a yielded promise is |
| 2176 | * rejected, the rejection error will be passed to {@code throw}. |
| 2177 | * |
| 2178 | * <p>Example 1: the Fibonacci Sequence. |
| 2179 | * <pre><code> |
| 2180 | * webdriver.promise.consume(function* fibonacci() { |
| 2181 | * var n1 = 1, n2 = 1; |
| 2182 | * for (var i = 0; i < 4; ++i) { |
| 2183 | * var tmp = yield n1 + n2; |
| 2184 | * n1 = n2; |
| 2185 | * n2 = tmp; |
| 2186 | * } |
| 2187 | * return n1 + n2; |
| 2188 | * }).then(function(result) { |
| 2189 | * console.log(result); // 13 |
| 2190 | * }); |
| 2191 | * </code></pre> |
| 2192 | * |
| 2193 | * <p>Example 2: a generator that throws. |
| 2194 | * <pre><code> |
| 2195 | * webdriver.promise.consume(function* () { |
| 2196 | * yield webdriver.promise.delayed(250).then(function() { |
| 2197 | * throw Error('boom'); |
| 2198 | * }); |
| 2199 | * }).thenCatch(function(e) { |
| 2200 | * console.log(e.toString()); // Error: boom |
| 2201 | * }); |
| 2202 | * </code></pre> |
| 2203 | * |
| 2204 | * @param {!Function} generatorFn The generator function to execute. |
| 2205 | * @param {Object=} opt_self The object to use as "this" when invoking the |
| 2206 | * initial generator. |
| 2207 | * @param {...*} var_args Any arguments to pass to the initial generator. |
| 2208 | * @return {!webdriver.promise.Promise.<?>} A promise that will resolve to the |
| 2209 | * generator's final result. |
| 2210 | * @throws {TypeError} If the given function is not a generator. |
| 2211 | */ |
| 2212 | webdriver.promise.consume = function(generatorFn, opt_self, var_args) { |
| 2213 | if (!webdriver.promise.isGenerator(generatorFn)) { |
| 2214 | throw TypeError('Input is not a GeneratorFunction: ' + |
| 2215 | generatorFn.constructor.name); |
| 2216 | } |
| 2217 | |
| 2218 | var deferred = webdriver.promise.defer(); |
| 2219 | var generator = generatorFn.apply(opt_self, goog.array.slice(arguments, 2)); |
| 2220 | callNext(); |
| 2221 | return deferred.promise; |
| 2222 | |
| 2223 | /** @param {*=} opt_value . */ |
| 2224 | function callNext(opt_value) { |
| 2225 | pump(generator.next, opt_value); |
| 2226 | } |
| 2227 | |
| 2228 | /** @param {*=} opt_error . */ |
| 2229 | function callThrow(opt_error) { |
| 2230 | // Dictionary lookup required because Closure compiler's built-in |
| 2231 | // externs does not include GeneratorFunction.prototype.throw. |
| 2232 | pump(generator['throw'], opt_error); |
| 2233 | } |
| 2234 | |
| 2235 | function pump(fn, opt_arg) { |
| 2236 | if (!deferred.isPending()) { |
| 2237 | return; // Defererd was cancelled; silently abort. |
| 2238 | } |
| 2239 | |
| 2240 | try { |
| 2241 | var result = fn.call(generator, opt_arg); |
| 2242 | } catch (ex) { |
| 2243 | deferred.reject(ex); |
| 2244 | return; |
| 2245 | } |
| 2246 | |
| 2247 | if (result.done) { |
| 2248 | deferred.fulfill(result.value); |
| 2249 | return; |
| 2250 | } |
| 2251 | |
| 2252 | webdriver.promise.asap(result.value, callNext, callThrow); |
| 2253 | } |
| 2254 | }; |