forked from bnoguchi/everyauth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.js
93 lines (88 loc) · 2.48 KB
/
promise.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
var Promise = function (values) {
this._callbacks = [];
this._errbacks = [];
this._timebacks = [];
if (arguments.length > 0) {
this.fulfill.apply(this, values);
}
};
Promise.prototype = {
callback: function (fn, scope) {
if (this.values) {
fn.apply(scope, this.values);
return this;
}
this._callbacks.push([fn, scope]);
return this;
}
, errback: function (fn, scope) {
if (this.err) {
fn.call(scope, this.err);
return this;
}
this._errbacks.push([fn, scope]);
return this;
}
, timeback: function (fn, scope) {
if (this.timedOut) {
fn.call(scope);
return this;
}
this._timebacks.push([fn, scope]);
return this;
}
, fulfill: function () {
if (this.isFulfilled) return;
this.isFulfilled = true;
if (this._timeout) clearTimeout(this._timeout);
var callbacks = this._callbacks;
this.values = arguments;
for (var i = 0, l = callbacks.length; i < l; i++) {
callbacks[i][0].apply(callbacks[i][1], arguments);
}
return this;
}
, fail: function (err) {
if (this._timeout) clearTimeout(this._timeout);
var errbacks = this._errbacks;
if ('string' === typeof err)
err = new Error(err);
this.err = err;
for (var i = 0, l = errbacks.length; i < l; i++) {
errbacks[i][0].call(errbacks[i][1], err);
}
return this;
}
, timeout: function (ms) {
if (this.values || this.err) return this;
var timebacks = this._timebacks
, self = this;
if (ms === -1) return this;
this._timeout = setTimeout(function () {
self.timedOut = true;
for (var i = 0, l = timebacks.length; i < l; i++) {
timebacks[i][0].call(timebacks[i][1]);
}
}, ms);
return this;
}
};
var ModulePromise = module.exports = function (_module, values) {
if (values)
Promise.call(this, values);
else
Promise.call(this);
this.module = _module;
};
ModulePromise.prototype.__proto__ = Promise.prototype;
ModulePromise.prototype.breakTo = function (seqName) {
if (this._timeout) clearTimeout(this._timeout);
var args = Array.prototype.slice.call(arguments, 1);
var _module = this.module
, seq = _module._stepSequences[seqName];
if (_module.everyauth.debug)
console.log('breaking out to ' + seq.name);
seq = seq.materialize();
seq.start.apply(seq, args);
// TODO Garbage collect the abandoned sequence
};