# Class webdriver.promise.ControlFlow

code »

    webdriver.EventEmitter
      └ webdriver.promise.ControlFlow

Handles the execution of scheduled tasks, each of which may be an asynchronous operation. The control flow will ensure tasks are executed in the ordered scheduled, starting each task only once those before it have completed.

Each task scheduled within this flow may return a `webdriver.promise.Promise` to indicate it is an asynchronous operation. The ControlFlow will wait for such promises to be resolved before marking the task as completed.

Tasks and each callback registered on a `webdriver.promise.Deferred` will be run in their own ControlFlow frame. Any tasks scheduled within a frame will have priority over previously scheduled tasks. Furthermore, if any of the tasks in the frame fails, the remainder of the tasks in that frame will be discarded and the failure will be propagated to the user through the callback/task's promised result.

Each time a ControlFlow empties its task queue, it will fire an `webdriver.promise.ControlFlow.EventType.IDLE` event. Conversely, whenever the flow terminates due to an unhandled error, it will remove all remaining tasks in its queue and fire an `webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION` event. If there are no listeners registered with the flow, the error will be rethrown to the global error handler.

## Constructor

webdriver.promise.ControlFlow ( opt_timer )

Parameters
opt_timer: `webdriver.promise.ControlFlow.Timer=` The timer object to use. Should only be set for testing.

## Enumerations

webdriver.promise.ControlFlow.EventType Events that may be emitted by an `webdriver.promise.ControlFlow`.

Show:Public Protected Private

## Type Definitions

code »webdriver.promise.ControlFlow.Timer : `{clearInterval: function(number), clearTimeout: function(number), setInterval: function(!Function, number): number, setTimeout: function(!Function, number): number}`
No description.

## Instance Methods

### Defined in `webdriver.promise.ControlFlow`

code »abortFrame_ ( error )

Aborts the current frame. The frame, and all of the tasks scheduled within it will be discarded. If this instance does not have an active frame, it will immediately terminate all execution.

Parameters
error: `*` The reason the frame is being aborted; typically either an Error or string.

code »abortNow_ ( error )

Aborts this flow, abandoning all remaining tasks. If there are listeners registered, an `UNCAUGHT_EXCEPTION` will be emitted with the offending `error`, otherwise, the `error` will be rethrown to the global error handler.

Parameters
error: `*` Object describing the error that caused the flow to abort; usually either an Error or string value.

code »annotateError ( e ) ⇒ `!(Error|goog.testing.JsUnitException)`

Appends a summary of this instance's recent task history to the given error's stack trace. This function will also ensure the error's stack trace is in canonical form.

Parameters
e: `!(Error|goog.testing.JsUnitException)` The error to annotate.
Returns
The annotated error.

code »await ( promise ) ⇒ `!webdriver.promise.Promise`

Schedules a task that will wait for another promise to resolve. The resolved promise's value will be returned as the task result.

Parameters
promise: `!webdriver.promise.Promise` The promise to wait on.
Returns
A promise that will resolve when the task has completed.

code »cancelEventLoop_ ( )

Cancels the event loop, if necessary.

code »cancelShutdown_ ( )

Cancels the shutdown sequence if it is currently scheduled.

code »clearHistory ( )

Clears this instance's task history.

code »commenceShutdown_ ( )

Commences the shutdown sequence for this instance. After one turn of the event loop, this object will emit the `webdriver.promise.ControlFlow.EventType.IDLE` event to signal listeners that it has completed. During this wait, if another task is scheduled, the shutdown will be aborted.

code »execute ( fn, opt_description ) ⇒ `!webdriver.promise.Promise`

Schedules a task for execution. If there is nothing currently in the queue, the task will be executed in the next turn of the event loop.

Parameters
fn: `!Function` The function to call to start the task. If the function returns a `webdriver.promise.Promise`, this instance will wait for it to be resolved before starting the next task. opt_description: `string=` A description of the task.
Returns
A promise that will be resolved with the result of the action.

code »getHistory ( ) ⇒ `!Array.<string>`

Returns a summary of the recent task activity for this instance. This includes the most recently completed task, as well as any parent tasks. In the returned summary, the task at index N is considered a sub-task of the task at index N+1.

Returns
A summary of this instance's recent task activity.

code »getNextTask_ ( ) ⇒ `webdriver.promise.Task_`

Returns
The next task to execute, or `null` if a frame was resolved.

code »getSchedule ( ) ⇒ `string`

Returns
The scheduled tasks still pending with this instance.

code »reset ( )

Resets this instance, clearing its queue and removing all event listeners.

code »resolveFrame_ ( frame )

Parameters
frame: `!webdriver.promise.Frame_` The frame to resolve.

code »runEventLoop_ ( )

Executes the next task for the current frame. If the current frame has no more tasks, the frame's result will be resolved, returning control to the frame's creator. This will terminate the flow if the completed frame was at the top of the stack.

code »runInNewFrame_ ( fn, callback, errback, opt_activate )

Executes a function in a new frame. If the function does not schedule any new tasks, the frame will be discarded and the function's result returned immediately. Otherwise, a promise will be returned. This promise will be resolved with the function's result once all of the tasks scheduled within the function have been completed. If the function's frame is aborted, the returned promise will be rejected.

Parameters
fn: `!Function` The function to execute. callback: `function(*)` The function to call with a successful result. errback: `function(*)` The function to call if there is an error. opt_activate: `boolean=` Whether the active frame should be updated to the newly created frame so tasks are treated as sub-tasks.

code »scheduleEventLoopStart_ ( )

Schedules the interval for this instance's event loop, if necessary.

code »timeout ( ms, opt_description ) ⇒ `!webdriver.promise.Promise`

Inserts a `setTimeout` into the command queue. This is equivalent to a thread sleep in a synchronous programming language.

Parameters
ms: `number` The timeout delay, in milliseconds. opt_description: `string=` A description to accompany the timeout.
Returns
A promise that will be resolved with the result of the action.

code »trimHistory_ ( )

Removes a completed task from this instance's history record. If any tasks remain from aborted frames, those will be removed as well.

code »wait ( condition, timeout, opt_message ) ⇒ `!webdriver.promise.Promise`

Schedules a task that shall wait for a condition to hold. Each condition function may return any value, but it will always be evaluated as a boolean.

Condition functions may schedule sub-tasks with this instance, however, their execution time will be factored into whether a wait has timed out.

In the event a condition returns a Promise, the polling loop will wait for it to be resolved before evaluating whether the condition has been satisfied. The resolution time for a promise is factored into whether a wait has timed out.

If the condition function throws, or returns a rejected promise, the wait task will fail.

Parameters
condition: `!Function` The condition function to poll. timeout: `number` How long to wait, in milliseconds, for the condition to hold before timing out. opt_message: `string=` An optional error message to include if the wait times out; defaults to the empty string.
Returns
A promise that will be resolved when the condition has been satisified. The promise shall be rejected if the wait times out waiting for the condition.

### Defined in `webdriver.EventEmitter`

code »addListener ( type, listenerFn, opt_scope ) ⇒ `!webdriver.EventEmitter`

Registers a listener.

Parameters
type: `string` The type of event to listen for. listenerFn: `!Function` The function to invoke when the event is fired. opt_scope: `Object=` The object in whose scope to invoke the listener.
Returns
A self reference.

code »addListener_ ( type, listenerFn, opt_scope, opt_oneshot ) ⇒ `!webdriver.EventEmitter`

Registers a listener.

Parameters
type: `string` The type of event to listen for. listenerFn: `!Function` The function to invoke when the event is fired. opt_scope: `Object=` The object in whose scope to invoke the listener. opt_oneshot: `boolean=` Whether the listener should be removed after the first event is fired.
Returns
A self reference.

code »emit ( type, var_args )

Fires an event and calls all listeners.

Parameters
type: `string` The type of event to emit. var_args: `...*` Any arguments to pass to each listener.

code »listeners ( type ) ⇒ `!Array`

Returns a mutable list of listeners for a specific type of event.

Parameters
type: `string` The type of event to retrieve the listeners for.
Returns
The registered listeners for the given event type.

code »on ( type, listenerFn, opt_scope ) ⇒ `!webdriver.EventEmitter`

An alias for `#addListener()`.

Parameters
type: `string` The type of event to listen for. listenerFn: `!Function` The function to invoke when the event is fired. opt_scope: `Object=` The object in whose scope to invoke the listener.
Returns
A self reference.

code »once ( type, listenerFn, opt_scope ) ⇒ `!webdriver.EventEmitter`

Registers a one-time listener which will be called only the first time an event is emitted, after which it will be removed.

Parameters
type: `string` The type of event to listen for. listenerFn: `!Function` The function to invoke when the event is fired. opt_scope: `Object=` The object in whose scope to invoke the listener.
Returns
A self reference.

code »removeAllListeners ( opt_type ) ⇒ `!webdriver.EventEmitter`

Removes all listeners for a specific type of event. If no event is specified, all listeners across all types will be removed.

Parameters
opt_type: `string=` The type of event to remove listeners from.
Returns
A self reference.

code »removeListener ( type, listenerFn ) ⇒ `!webdriver.EventEmitter`

Removes a previously registered event listener.

Parameters
type: `string` The type of event to unregister. listenerFn: `!Function` The handler function to remove.
Returns
A self reference.

## Instance Properties

### Defined in `webdriver.promise.ControlFlow`

code »activeFrame_ : `webdriver.promise.Frame_`

Tracks the active execution frame for this instance. Lazily initialized when the first task is scheduled.

code »eventLoopId_ : `?number`

Interval ID for this instance's event loop.

code »history_ : `!Array`

A list of recent tasks. Each time a new task is started, or a frame is completed, the previously recorded task is removed from this list. If there are multiple tasks, task N+1 is considered a sub-task of task N.

code »numAbortedFrames_ : `number`

The number of aborted frames since the last time a task was executed or a frame completed successfully.

code »pendingRejections_ : `number`

The number of "pending" promise rejections.

Each time a promise is rejected and is not handled by a listener, it will schedule a 0-based timeout to check if it is still unrejected in the next turn of the JS-event loop. This allows listeners to attach to, and handle, the rejected promise at any point in same turn of the event loop that the promise was rejected.

When this flow's own event loop triggers, it will not run if there are any outstanding promise rejections. This allows unhandled promises to be reported before a new task is started, ensuring the error is reported to the current task queue.

code »schedulingFrame_ : `webdriver.promise.Frame_`

A reference to the frame in which new tasks should be scheduled. If `null`, tasks will be scheduled within the active frame. When forcing a function to run in the context of a new frame, this pointer is used to ensure tasks are scheduled within the newly created frame, even though it won't be active yet.

code »shutdownId_ : `?number`

Timeout ID set when the flow is about to shutdown without any errors being detected. Upon shutting down, the flow will emit an `webdriver.promise.ControlFlow.EventType.IDLE` event. Idle events always follow a brief timeout in order to catch latent errors from the last completed task. If this task had a callback registered, but no errback, and the task fails, the unhandled failure would not be reported by the promise system until the next turn of the event loop: // Schedule 1 task that fails. var result = webriver.promise.controlFlow().schedule('example', function() { return webdriver.promise.rejected('failed'); }); // Set a callback on the result. This delays reporting the unhandled // failure for 1 turn of the event loop. result.then(goog.nullFunction);

code »timer : `webdriver.promise.ControlFlow.Timer`

The timer used by this instance.

### Defined in `webdriver.EventEmitter`

code »events_ : `!Object`

Map of events to registered listeners.

## Static Properties

code »webdriver.promise.ControlFlow.ANNOTATION_PROPERTY_ : `string`

Property used to track whether an error has been annotated by `webdriver.promise.ControlFlow#annotateError`.

code »webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY : `number`

How often, in milliseconds, the event loop should run.

code »webdriver.promise.ControlFlow.defaultTimer : `webdriver.promise.ControlFlow.Timer`

The default timer object, which uses the global timer functions.

code »webdriver.promise.ControlFlow.superClass_ : `webdriver.EventEmitter.prototype`