OLD | NEW |
| (Empty) |
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. | |
4 | |
5 /** | |
6 * @constructor | |
7 * @class FunctionSequence to invoke steps in sequence | |
8 * | |
9 * @param steps array of functions to invoke in parallel | |
10 * @param callback callback to invoke on success | |
11 * @param failureCallback callback to invoke on failure | |
12 */ | |
13 function FunctionParallel(name, steps, logger, callback, failureCallback) { | |
14 // Private variables hidden in closure | |
15 this.currentStepIdx_ = -1; | |
16 this.failed_ = false; | |
17 this.steps_ = steps; | |
18 this.callback_ = callback; | |
19 this.failureCallback_ = failureCallback; | |
20 this.logger = logger; | |
21 this.name = name; | |
22 | |
23 this.remaining = this.steps_.length; | |
24 | |
25 this.nextStep = this.nextStep_.bind(this); | |
26 this.onError = this.onError_.bind(this); | |
27 this.apply = this.start.bind(this); | |
28 } | |
29 | |
30 | |
31 /** | |
32 * Error handling function, which fires error callback. | |
33 * | |
34 * @param err error message | |
35 */ | |
36 FunctionParallel.prototype.onError_ = function(err) { | |
37 if (!this.failed_) { | |
38 this.failed_ = true; | |
39 this.failureCallback_(err); | |
40 } | |
41 }; | |
42 | |
43 /** | |
44 * Advances to next step. This method should not be used externally. In external | |
45 * cases should be used nextStep function, which is defined in closure and thus | |
46 * has access to internal variables of functionsequence. | |
47 */ | |
48 FunctionParallel.prototype.nextStep_ = function() { | |
49 if (--this.remaining == 0 && !this.failed_) { | |
50 this.callback_(); | |
51 } | |
52 }; | |
53 | |
54 /** | |
55 * This function should be called only once on start, so start all the children | |
56 * at once | |
57 */ | |
58 FunctionParallel.prototype.start = function(var_args) { | |
59 this.logger.vlog('Starting [' + this.steps_.length + '] parallel tasks with ' | |
60 + arguments.length + ' argument(s)'); | |
61 if (this.logger.verbose) { | |
62 for (var j = 0; j < arguments.length; j++) { | |
63 this.logger.vlog(arguments[j]); | |
64 } | |
65 } | |
66 for (var i=0; i < this.steps_.length; i++) { | |
67 this.logger.vlog('Attempting to start step [' + this.steps_[i].name + ']'); | |
68 try { | |
69 this.steps_[i].apply(this, arguments); | |
70 } catch(e) { | |
71 this.onError(e.toString()); | |
72 } | |
73 } | |
74 }; | |
OLD | NEW |