promise.js
3.08 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
function Promise(fn) {
var promise = this;
promise._value = null;
promise._reason = function(){};
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) {
promise._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);
}
Promise.all = function(promises){
if (!Array.isArray(promises)) {
throw new TypeError('You must pass an array to all.');
}
return new Promise(function(resolve,reject){
var i = 0,
result = [],
len = promises.length,
count = len;
function resolver(index) {
return function(value) {
resolveAll(index, value);
};
}
function rejecter(reason){
reject(reason);
}
function resolveAll(index,value){
result[index] = value;
if( --count === 0){
resolve(result)
}
}
for (; i < len; i++) {
promises[i].then(resolver(i),rejecter);
}
});
};
Promise.race = function(promises){
if (!Array.isArray(promises)) {
throw new TypeError('You must pass an array to race.');
}
return new Promise(function(resolve,reject){
var i = 0,
len = promises.length;
function resolver(value) {
resolve(value);
}
function rejecter(reason){
reject(reason);
}
for (; i < len; i++) {
promises[i].then(resolver,rejecter);
}
});
};
module.exports = Promise;