0%

实现promise(转自bananas)

promise 是为了解决回调地狱的问题。
主要有以下几个方法

  1. Promise.prototype.then
  2. Promise.prototype.catch
  3. Promise.all
  4. Promise.race
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
131
132
133
134
135
const log = console.log.bind(console)

class BananasPromise {
constructor(func) {
if(typeof func !== 'function') {
throw new Error(func, 'is no a function')
}
this.func = func
this.state = 'init'
const resolve = this.resolve.bind(this)
const reject = this.reject.bind(this)
const r = () => {
func(resolve, reject)
return this
}
return r
}

_efunc() {

}

then(done) {
this.done = done || this._efunc
if(this.state === 'done') {
done(this.args)
}
return this
}

catch(fail) {
this.fail = fail || this._efunc
if(this.state === 'fail') {
fail(this.err)
}
}

resolve(args='') {
this.state = 'done'
this.args = args
this.done && this.then(this.done)
}

reject(args='') {
this.state = 'fail'
this.err = args
this.catch && this.catch(this.fail)
}

static _init() {
const cls = this
cls.state = 'init'
cls.done = () => {}
cls.fail = () => {}
cls._resule = []
cls._err = null
}

static all(array) {
const cls = this
let len = array.length
cls._init()
array.forEach((i, index) => {
if(cls._err !== null) {
return
}
i().then((a) => {
if(cls._err !== null) {
return
}
len--
cls._resule[index] = a
if(len === 0) {
cls.state = 'done'
cls.then()
}
}).catch((err) => {
if(cls._err !== null) {
return
}
cls.state = 'fail'
cls._err = err
cls.catch()
})
})
return this
}

static then(done) {
const cls = this
if(this.state === 'done') {
cls.done(cls._resule)
} else if(this.state === 'init') {
cls.done = done || cls.done
}
return this
}

static catch(fail) {
const cls = this
if(cls.state === 'fail') {
cls.fail(cls._err)
} else if(cls.state === 'init') {
cls.fail = fail || cls.fail
}
}

static race(array) {
const cls = this
cls._init()
array.forEach((item) => {
if(cls.state === 'done' || cls.state === 'fail') {
return
}
item().then((data) => {
if(cls.state === 'done' || cls.state === 'fail') {
return
}
cls.state = 'done'
cls._resule = data
cls.then()
}).catch((err) => {
if(cls.state === 'done' || cls.state === 'fail') {
return
}
cls.state = 'fail'
cls._err = err
cls.catch()
})
})
return cls
}
}