-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise4.js
43 lines (40 loc) · 938 Bytes
/
promise4.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
// 解决Promise串行链式的延续问题,每次then都需要返回一个promise
class Promise {
constructor (executor) {
this.value = undefined
this.status = 'pending'
this.children = []
executor(value => {
this.status = 'resolve',
this.setValue(value)
}, reason => {
this.status = 'rejected'
this.setValue(reason)
})
}
then(onResolved) {
var child = new Promise(() => {})
child.onResolved = onResolved
this.children.push(child)
return this
}
setValue (value) {
this.value = value
this.children.forEach(child => {
var ret = child.onResolved(this.value)
this.value = ret
})
}
}
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('promise1')
},300)
})
promise.then(value1 => {
console.log('value1',value1)
value1 = 'promise2'
return value1
}).then(value2 => {
console.log('value2',value2)
})