实现一个promise

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
const PENDING = Symbol();
const FULFILLED = Symbol();
const REJECTED = Symbol();

function Promisee(fn){
if(typeof fn != 'function'){
throw new Error('resolver must be a function');
}
let state = PENDING;
let value = null;
let handler = [];

function fulfill(result){
state = FULFILLED;
value = result;
handler.forEach(next)
handler = []
}
function reject(err){
state = REJECTED;
value = err;
handler.forEach(next)
handler = []
}
function resolve(result){
try{
let then = typeof result.then === 'function'? result.then:null
if(then){
then.bind(result)(resolve,reject)
return
}
fulfill(result)
} catch(err){
reject(err)
}
}
function next({onFulfill,onReject}){
switch(state){
case FULFILLED:
onFulfill && onFulfill(value);
break;
case REJECTED:
onReject && typeof(onReject) == 'function' && onReject(value);
break;
case PENDING:
handler.push({ onFulfill, onReject })
}
}
this.then = function(onFulfill,onReject){
return new Promisee((resolve,reject)=>{
next({
onFulfill: (val) => {
resolve(onFulfill(val))
},
onReject: (err) =>{
reject(onReject(err))
}
})
})
}
this.catch = (reject)=>{
if(state === REJECTED){
reject(value)
}
return this;
}
fn(resolve,reject)
}

function sleep(sec){
return new Promisee((resolve,reject) => {
setTimeout(() => resolve(sec),sec * 1000)
})
}

var p = new Promisee((r,j)=>{
r('resolve')
})
p.then((val)=>{
console.log(val)
return sleep(1)
})
.then(val=>{
console.log(val)
return sleep(val + 1)
})
.then(val=>{
console.log(val)
return sleep(val + 1)
})
.then(console.log)

.catch(err=>console.log('err:',err))