function noop(){}
function chain(delegateFn, explicitDone){
var onDoneFn = noop;
var onErrorFn = function(e){
console.error(e.stack || e);
process.exit(-1);
};
var waitForCount = 1;
delegateFn = delegateFn || noop;
var stackError = new Error('capture stack');
function decrementWaitFor() {
waitForCount--;
if (waitForCount == 0)
onDoneFn();
}
function self(){
try {
return delegateFn.apply(self, arguments);
} catch (error) {
self.error(error);
} finally {
if (!explicitDone)
decrementWaitFor();
}
};
self.onDone = function(callback){
onDoneFn = callback;
return self;
};
self.onError = function(callback){
onErrorFn = callback;
return self;
};
self.waitFor = function(callback){
if (waitForCount == 0)
throw new Error("Can not wait on already called callback.");
waitForCount++;
return chain(callback).onDone(decrementWaitFor).onError(self.error);
};
self.waitMany = function(callback){
if (waitForCount == 0)
throw new Error("Can not wait on already called callback.");
waitForCount++;
return chain(callback, true).onDone(decrementWaitFor).onError(self.error);
};
self.done = function(callback){
decrementWaitFor();
};
self.error = function(error) {
var stack = stackError.stack.split(/\n\r?/).splice(2);
var nakedStack = [];
stack.forEach(function(frame){
if (!frame.match(/callback\.js:\d+:\d+\)$/))
nakedStack.push(frame);
});
error.stack = error.stack + '\nCalled from:\n' + nakedStack.join('\n');
onErrorFn(error);
};
return self;
}
exports.chain = chain;
f6a7e35dd6'>treecommitdiffstats
blob: fb5845d320f2c2fa6c6915f1a2de24a302fd0ed3 (
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
|
function Users(server, controlBar) {
this.server = server;
this.controlBar = controlBar;
};
extend(Users.prototype, {
'fetchCurrentUser':function(callback) {
var self = this;
this.server.request("GET", "/account.json", {}, function(code, response){
self['current'] = response['user'];
callback(response['user']);
});
},
'logout': function(callback) {
var self = this;
this.controlBar.logout(function(){
delete self['current'];
(callback||noop)();
});
},
'login': function(callback) {
var self = this;
this.controlBar.login(function(){
self['fetchCurrentUser'](function(){
(callback||noop)();
});
});
},
'notAuthorized': function(){
this.controlBar.notAuthorized();
}
});
|