-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsp.js
130 lines (126 loc) · 3.41 KB
/
sp.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
window.postError = undefined
function MyPromise(fn) {
let value = null;
let callback = [];
let status = 'pending';
function resolve(val) {
if(status === 'pending') {
if(val.then && typeof val.then === 'function') {
then.call(val, resolve);
return;
}
}
status = 'resolved';
value = val;
setTimeout(function(){
callback.forEach(function(i) {bridgePromise(i);});
}, 0);
}
function reject(val) {
window.postError = 0
if(status === 'pending') {
if(val.then && typeof val.then === 'function') {
catch.call(val, reject);
return;
}
}
status = 'rejected';
value = val;
setTimeout(function(){
callback.forEach(function(i) {bridgePromise(i);});
}, 0);
}
this.then = function(onfull) {
return new MyPromise(function(resol, rejec){
bridgePromise({
resolve: resol,
reject: rejec,
onFufill: onfull || null,
onReject: null,
});
});
}
this.catch = function(onReject) {
window.postError = 1
return new MyPromise(function(resol, rejec){
bridgePromise({
resolve: resol,
reject: rejec,
onFufill: null,
onReject: onReject || null,
});
});
}
function bridgePromise(obj) {
if(status === 'pending') {
callback.push(obj);
return;
}
let cb = null;
let ret = null;
cb = status === 'resolved' ? obj.onFufill : obj.onReject;
if(!cb) {
status === 'resolved' ? obj.resolve(value) : obj.reject(value);
return;
}
ret = cb(value);
status === 'resolved' ? obj.resolve(ret) : obj.reject(ret);
}
try {
fn(resolve, reject);
} catch(err) {
reject(err);
setTimeout(function() {
if(window.postError === 0) {
window.postError = undefined
throw new Error('unhandleRejection');
}
window.postError = undefined;
})
}
}
MyPromise.all = function(allPs) {
return new MyPromise(function(resolve, reject) {
let vals = []
for(let i = 0; i < allPs.length; i++) {
new MyPromise(function(res, rej) {
res(allPs[i]);
}).then(val => {
vals.push(val);
if(vals.length === allPs.length) {
resolve(vals);
}
});
}
})
}
MyPromise.race = function(allPs) {
return new MyPromise(function(resolve, reject) {
for(let i = 0; i < allPs.length; i++) {
new MyPromise(function(res, rej) {
res(allPs[i]);
}).then(val => {
resolve(val);
});
}
})
}
MyPromise.order = function(arr) {
let t = arr[0];
let container = [];
for(let i = 1; i < arr.length + 1; i++) {
t = t.then(v => {
container.push(v);
if(i === arr.length) {
return MyPromise.resolve(container);
}
return arr[i]
})
}
return t;
}
MyPromise.resolve = function(v) {
return new MyPromise(function(res){
res(v);
});
}