-
Notifications
You must be signed in to change notification settings - Fork 3
/
thenableFactory.js
69 lines (59 loc) · 1.69 KB
/
thenableFactory.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
module.exports = function() {
function isThenable(obj) {
return obj && (obj instanceof Object) && typeof obj.then==="function";
}
function resolution(p,r,how) {
try {
/* 2.2.7.1 */
var x = how ? how(r):r ;
if (p===x) /* 2.3.1 */
return p.reject(new TypeError("Promise resolution loop")) ;
if (isThenable(x)) {
/* 2.3.3 */
x.then(function(y){
resolution(p,y);
},function(e){
p.reject(e)
}) ;
} else {
p.resolve(x) ;
}
} catch (ex) {
/* 2.2.7.2 */
p.reject(ex) ;
}
}
function _unchained(v){}
function thenChain(res,rej){
this.resolve = res;
this.reject = rej;
}
function Chained() {};
Chained.prototype = {
resolve:_unchained,
reject:_unchained,
then:thenChain
};
function then(res,rej){
var chain = new Chained() ;
try {
this._resolver(function(value) {
return isThenable(value) ? value.then(res,rej) : resolution(chain,value,res);
},function(ex) {
resolution(chain,ex,rej) ;
}) ;
} catch (ex) {
resolution(chain,ex,rej);
}
return chain ;
}
function Thenable(resolver) {
this._resolver = resolver ;
this.then = then ;
};
Thenable.resolve = function(v){
return Thenable.isThenable(v) ? v : {then:function(resolve){return resolve(v)}};
};
Thenable.isThenable = isThenable ;
return Thenable ;
} ;