-
Notifications
You must be signed in to change notification settings - Fork 0
/
PromiseA.js
95 lines (88 loc) · 2.29 KB
/
PromiseA.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
94
95
export function PromiseA(callback) {
var self = this;
self.__state = 'Pending';
var fulfill = function(params) {
self.__state = 'Fulfilled';
if (self.__fulfilled) {
setTimeout(function() {
self.__fulfilled.forEach((onFulfilled, index) => {
delete self.__fulfilled[index];
onFulfilled(params);
});
}, 0);
}
self.__params = params;
};
self.__fulfill = fulfill;
var reject = function(error) {
self.__state = 'Rejected';
if (self.__rejected) {
setTimeout(function() {
self.__rejected.forEach((onFulfilled, index) => {
delete self.__rejected[index];
onFulfilled(error);
});
}, 0);
}
self.__reason = error;
};
self.__reject = reject;
callback(fulfill, reject);
}
PromiseA.prototype.then = function(onFulfilled, onRejected) {
var self = this;
return new PromiseA(function(thenPromiseeFulfill, thenPromiseeReject) {
var thenable;
var fulfilled = function(fulfill) {
if (fulfill && fulfill.then) {
thenable = fulfill.then;
if (typeof thenable === 'function') {
fulfill.then(
function(fulfill) {
thenPromiseeFulfill(onFulfilled(fulfill));
},
function(error) {
thenPromiseeReject(onRejected(error));
}
);
}
} else {
if (typeof onFulfilled === 'function') {
thenPromiseeFulfill(onFulfilled(fulfill));
}
}
};
if (!self.__fulfilled) {
self.__fulfilled = [];
}
self.__fulfilled.push(fulfilled);
var rejected = function(error) {
if (typeof onRejected === 'function') {
thenPromiseeReject(onRejected(error));
} else {
this.__reject(this.__reason);
}
};
if (!self.__rejected) {
self.__rejected = [];
}
self.__rejected.push(rejected);
if (self.__state !== 'Pending') {
if (self.__state === 'Fulfilled') {
self.__fulfill(self.__params);
} else {
self.__reject(self.__reason);
}
}
});
};
PromiseA.resolve = function(params) {
return new PromiseA(function(fulfill) {
fulfill(params);
});
};
PromiseA.reject = function(reason) {
return new PromiseA(function(fulfill, reject) {
reject(reason);
});
};