-
Notifications
You must be signed in to change notification settings - Fork 0
/
mypromise.js
84 lines (80 loc) · 2.16 KB
/
mypromise.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
const State = {
PENDING: 0,
FULFILLED: 1,
REJECTED: 2
}
class MyPromise{
constructor(fn){
this.state = State.PENDING
this.value = null
this.handler = null
fn(this.fulfilled.bind(this), this.rejected.bind(this))
}
fulfilled(result){
this.state = State.FULFILLED
this.value = result
this.handler && this.handler.fulfilledCb(result)
}
rejected(){
this.state = State.REJECTED
this.value = result
this.handler && this.handler.rejectedCb(result)
}
handleFunc(handler){
if(this.state == State.PENDING){
this.handler = handler
} else if(this.state == State.FULFILLED && typeof handler.fulfilledCb === 'function'){
handler.fulfilledCb(this.value)
this.handler = null
} else if(this.state == State.REJECTED && typeof handler.rejectedCb === 'function'){
handler.rejectedCb(this.value)
this.handler = null
}
}
then(fulfilledCb, rejectedCb){
return new MyPromise((resolve, reject)=>{
this.handleFunc({fulfilledCb: function(res){
resolve(fulfilledCb(res))
}, rejectedCb: function(err){
try{
reject(rejectedCb(err))
}catch(exp){
reject(exp)
}
}})
})
}
static resolve(value){
return new MyPromise((_resolve, _reject)=>{
_resolve(value)
})
}
static reject(value){
return new MyPromise((_resolve, _reject)=>{
_reject(value)
})
}
static all(promiseList){
//to do....
let values = Array.prototype.slice.call(promiseList)
return new MyPromise(function(resolve, reject){
let len = promiseList.length
function res(i, item){
if (item instanceof MyPromise && item.then === MyPromise.prototype.then) {
item.then(function (val) {
res(i, val);
}, reject)
return
}
values[i] = item
len -= 1
if(len === 0){
resolve(values)
}
}
for (let i = 0; i < promiseList.length; i++) {
res(i, promiseList[i])
}
})
}
}