-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathpromise-2-async.js
65 lines (58 loc) · 1.08 KB
/
promise-2-async.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
/**
* Created by Capricorncd.
* https://github.com/capricorncd
* Date: 2020-06-07 10:47
*/
/**
* 加入延迟机制(异步)
*/
class ZxPromise {
callbacks = []
constructor (fn) {
fn(this._resolveHandler.bind(this))
}
/**
* then
*
* Promises/A+规范要求,then 方法能够链式调用,return this
* https://promisesaplus.com/
* @param onFulfilled
*/
then (onFulfilled) {
this.callbacks.push(onFulfilled)
return this
}
_resolveHandler (value) {
setTimeout(() => {
this.callbacks.forEach(fn => fn(value))
}, 0)
}
}
/**
* 成功案例
*/
new ZxPromise(resolve => {
console.log('test2')
resolve('test2')
}).then(res => {
console.log('test2 then', res)
})
/**
* 失败案例
* @type {ZxPromise}
*/
const zp = new ZxPromise(resolve => {
console.log('test3')
resolve('test3')
})
zp.then(res => {
console.log('test3 then1,', res)
})
/**
* 在 resolve 执行后,再通过 then 注册上来的 onFulfilled 不能被执行。
*/
setTimeout(() => {
zp.then(res => {
console.log('test3 then2,', res)
})
})