forked from huanshen/Promise
-
Notifications
You must be signed in to change notification settings - Fork 1
/
promise5.js
42 lines (35 loc) · 1.13 KB
/
promise5.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
// 添加了对promise对象的判断
function Promise(fn) {
var promise = this,
value = null;
promise._resolves = [];
promise._status = 'PENDING';
this.then = function (onFulfilled) {
return new Promise(function(resolve) {
function handle(value) {
var ret = typeof onFulfilled === 'function' && onFulfilled(value) || value;
if( ret && typeof ret ['then'] == 'function'){
ret.then(function(value){
resolve(value);
});
} else {
resolve(ret);
}
}
if (promise._status === 'PENDING') {
promise._resolves.push(handle);
} else if(promise._status === FULFILLED){
handle(value);
}
})
};
function resolve(value) {
setTimeout(function(){
promise._status = "FULFILLED";
promise._resolves.forEach(function (callback) {
value = callback.call(promise, value);
})
},0);
}
fn(resolve);
}