forked from huanshen/Promise
-
Notifications
You must be signed in to change notification settings - Fork 1
/
promise6.js
63 lines (54 loc) · 1.85 KB
/
promise6.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
// 添加拒绝方法,添加一个数组方法存放
function Promise(fn) {
var promise = this;
promise._value;
promise._reason;
promise._resolves = [];
promise._rejects = [];
promise._status = 'PENDING';
this.then = function (onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
function handle(value) {
var ret = typeof onFulfilled === 'function' && onFulfilled(value) || value;
if(ret && typeof ret ['then'] == 'function'){
ret.then(function(value){
resolve(value);
},function(reason){
reject(reason);
});
} else {
resolve(ret);
}
}
function errback(reason){
reason = typeof onRejected === 'function' && onRejected(reason) || reason;
reject(reason);
}
if (promise._status === 'PENDING') {
promise._resolves.push(handle);
promise._rejects.push(errback);
} else if(promise._status === 'FULFILLED'){
handle(promise._value);
} else if(promise._status === 'REJECTED') {
errback(promise._reason);
}
})
};
function resolve(value) {
setTimeout(function(){
promise._status = "FULFILLED";
promise._resolves.forEach(function (callback) {
value = callback( value);
})
},0);
}
function reject(value) {
setTimeout(function(){
promise._status = "REJECTED";
promise._rejects.forEach(function (callback) {
promise._reason = callback(value);
})
},0);
}
fn(resolve, reject);
}