aboutsummaryrefslogtreecommitdiffstats
path: root/src/scenario/Future.js
blob: 30c2d902e7032671a06f85626d0be0a06a3f4518 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
 * A future action in a spec.
 */
angular.scenario.Future = function(name, behavior) {
  this.name = name;
  this.behavior = behavior;
  this.fulfilled = false;
  this.value = undefined;
  this.parser = angular.identity;
};

/**
 * Executes the behavior of the closure.
 *
 * @param {Function} Callback function(error, result)
 */
angular.scenario.Future.prototype.execute = function(doneFn) {
  this.behavior(angular.bind(this, function(error, result) {
    this.fulfilled = true;
    if (result) {
      try {
        result = this.parser(result);
      } catch(e) {
        error = e;
      }
    }
    this.value = error || result;
    doneFn(error, result);
  }));
};

/**
 * Configures the future to convert it's final with a function fn(value)
 */
angular.scenario.Future.prototype.parsedWith = function(fn) {
  this.parser = fn;
  return this;
};

/**
 * Configures the future to parse it's final value from JSON
 * into objects.
 */
angular.scenario.Future.prototype.fromJson = function() {
  return this.parsedWith(angular.fromJson);
};

/**
 * Configures the future to convert it's final value from objects
 * into JSON.
 */
angular.scenario.Future.prototype.toJson = function() {
  return this.parsedWith(angular.toJson);
};