UNPKG

1.46 kBJavaScriptView Raw
1function AsyncResolvers(onFailedOne, onResolvedAll) {
2 this.onResolvedAll = onResolvedAll;
3 this.onFailedOne = onFailedOne;
4 this.resolvers = {};
5 this.resolversCount = 0;
6 this.passed = [];
7 this.failed = [];
8 this.firing = false;
9}
10
11AsyncResolvers.prototype = {
12
13 /**
14 * Add resolver
15 *
16 * @param {Rule} rule
17 * @return {integer}
18 */
19 add: function(rule) {
20 var index = this.resolversCount;
21 this.resolvers[index] = rule;
22 this.resolversCount++;
23 return index;
24 },
25
26 /**
27 * Resolve given index
28 *
29 * @param {integer} index
30 * @return {void}
31 */
32 resolve: function(index) {
33 var rule = this.resolvers[index];
34 if (rule.passes === true) {
35 this.passed.push(rule);
36 } else if (rule.passes === false) {
37 this.failed.push(rule);
38 this.onFailedOne(rule);
39 }
40
41 this.fire();
42 },
43
44 /**
45 * Determine if all have been resolved
46 *
47 * @return {boolean}
48 */
49 isAllResolved: function() {
50 return (this.passed.length + this.failed.length) === this.resolversCount;
51 },
52
53 /**
54 * Attempt to fire final all resolved callback if completed
55 *
56 * @return {void}
57 */
58 fire: function() {
59
60 if (!this.firing) {
61 return;
62 }
63
64 if (this.isAllResolved()) {
65 this.onResolvedAll(this.failed.length === 0);
66 }
67
68 },
69
70 /**
71 * Enable firing
72 *
73 * @return {void}
74 */
75 enableFiring: function() {
76 this.firing = true;
77 }
78
79};
80
81module.exports = AsyncResolvers;