1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 * @class FunctionSequence to invoke steps in sequence
8 * @param {string} name Name of the function.
9 * @param {Array.<function>} steps Array of functions to invoke in parallel.
10 * @param {Object} logger Logger object.
11 * @param {function()} callback Callback to invoke on success.
12 * @param {function(string)} failureCallback Callback to invoke on failure.
15 function FunctionParallel(name, steps, logger, callback, failureCallback) {
16 // Private variables hidden in closure
17 this.currentStepIdx_ = -1;
20 this.callback_ = callback;
21 this.failureCallback_ = failureCallback;
25 this.remaining = this.steps_.length;
27 this.nextStep = this.nextStep_.bind(this);
28 this.onError = this.onError_.bind(this);
29 this.apply = this.start.bind(this);
34 * Error handling function, which fires error callback.
36 * @param {string} err Error message.
39 FunctionParallel.prototype.onError_ = function(err) {
42 this.failureCallback_(err);
47 * Advances to next step. This method should not be used externally. In external
48 * cases should be used nextStep function, which is defined in closure and thus
49 * has access to internal variables of functionsequence.
53 FunctionParallel.prototype.nextStep_ = function() {
54 if (--this.remaining == 0 && !this.failed_) {
60 * This function should be called only once on start, so start all the children
62 * @param {...} var_args Arguments to be passed to all the steps.
64 FunctionParallel.prototype.start = function(var_args) {
65 this.logger.vlog('Starting [' + this.steps_.length + '] parallel tasks ' +
66 'with ' + arguments.length + ' argument(s)');
67 if (this.logger.verbose) {
68 for (var j = 0; j < arguments.length; j++) {
69 this.logger.vlog(arguments[j]);
72 for (var i = 0; i < this.steps_.length; i++) {
73 this.logger.vlog('Attempting to start step [' + this.steps_[i].name + ']');
75 this.steps_[i].apply(this, arguments);
77 this.onError(e.toString());