Debian Codegraph @

debian/tests/test_modules/hbs/lib/async.js

raw
1 /// provides the async helper functionality
2
3 function Waiter() {
4 if (!(this instanceof Waiter)) {
5 return new Waiter();
6 }
7
8 var self = this;
9
10 // found values
11 self.values = {};
12
13 // callback when done
14 self.callback = null;
15
16 self.resolved = false;
17
18 self.count = 0;
19 };
20
21 Waiter.prototype.wait = function() {
22 var self = this;
23 ++self.count;
24 };
25
26 // resolve the promise
27 Waiter.prototype.resolve = function(name, val) {
28 var self = this;
29
30 self.values[name] = val;
31
32 // done with all items
33 if (--self.count === 0) {
34 self.resolved = true;
35
36 // we may not have a done callback yet
37 if (self.callback) {
38 self.callback(self.values);
39 }
40 }
41 };
42
43 // sets the done callback for the waiter
44 // notifies when the promise is complete
45 Waiter.prototype.done = function(fn) {
46 var self = this;
47
48 self.callback = fn;
49 if (self.resolved) {
50 fn(self.values);
51 }
52 };
53
54 var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_';
55
56 var gen_id = function() {
57 var res = '';
58 for (var i=0 ; i<8 ; ++i) {
59 res += alphabet[Math.floor(Math.random() * alphabet.length)];
60 }
61
62 return res;
63 };
64
65 module.exports = function() {
66 // baton which contains the current
67 // set of deferreds
68 var waiter;
69
70 var obj = Object.create(null);
71 obj.done = function done(fn) {
72 // no async things called
73 if (!waiter) {
74 return fn({});
75 }
76
77 waiter.done(fn);
78
79 // clear the waiter for the next template
80 waiter = undefined;
81 };
82
83 obj.resolve = function resolve(fn, args) {
84 // we want to do async things, need a waiter for that
85 if (!waiter) {
86 waiter = new Waiter();
87 }
88
89 var id = '__' + gen_id() + '__';
90
91 var cur_waiter = waiter;
92 waiter.wait();
93
94 args = [].slice.call(args);
95 args.push(function(res) {
96 cur_waiter.resolve(id, res);
97 })
98
99 fn.apply(null, args);
100
101 // return the id placeholder
102 // this will be replaced later
103 return id;
104 };
105
106 return obj;
107 };