-
Notifications
You must be signed in to change notification settings - Fork 0
/
promiseMethods.js
95 lines (91 loc) · 2.38 KB
/
promiseMethods.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
85
86
87
88
89
90
91
92
93
94
95
function all(promises) {
let res = []
let count = 0
return new Promise((resolve, reject) => {
function settlePro(index, val) {
res[index] = val
count++
if (count === promises.length) {
resolve(res)
}
}
promises.forEach((promise, index) => {
if(promise instanceof Promise) {
promise.then((res) => {
settlePro(index, res)
}, err => reject(err))
} else {
settlePro(index, promise)
}
})
})
}
function race(promises) {
return new Promise((resolve, reject) => {
promises.forEach((promise, index) => {
if (promise instanceof Promise) {
promise.then(res => {
resolve(res)
},err => reject(err))
} else {
resolve(promise)
}
})
})
}
function settled(promises) {
let res = []
let count = 0
return new Promise((resolve, reject) => {
function check () {
if (promises.length === count) {
resolve(res)
}
}
promises.forEach((promise, index) => {
if (promise instanceof Promise) {
promise.then(res => {
res[index] = res
count++
check()
}, err => {
res[index] = err
count++
check()
})
} else {
res[index] = promise
count++
check()
}
})
})
}
function any (promises) {
let count = 0
return new Promise((resolve, reject) => {
promises.forEach(promise => {
if (promise instanceof Promise) {
promise.then(res => {
resolve(res)
}, err => {
count++
if (count === promise.length) {
reject(new Error('No Promise Resolve'))
}
})
} else {
resolve(promise)
}
})
})
}
Promise.prototype.myFinally = function(callback) {
this.then(res => {
callback()
return res
}, err => {
callback()
return res
})
}