forked from qianlongo/fe-handwriting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
66.Promise.allSettled.js
89 lines (75 loc) · 1.7 KB
/
66.Promise.allSettled.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
Promise.myAllSettled = (promises) => {
return new Promise((resolve, reject) => {
if (!Array.isArray(promises)) {
return reject('Promise.allSettled accepts an array')
}
const length = promises.length
let remaining = length
const result = []
if (length === 0) {
return resolve([])
}
const response = (i, value) => {
if (value instanceof Promise) {
// 注意此val非value
value.then((val) => {
response(i, val)
}, (err) => {
result[i] = {
status: 'rejected',
reason: err
}
if (--remaining === 0){
resolve(result)
}
})
return
}
result[ i ] = {
status: 'fulfilled',
value
}
if (--remaining === 0) {
resolve(result)
}
}
for (let i = 0; i < length; i++) {
response(i, promises[i])
}
})
}
Promise.myAllSettled2 = (promises) => {
return new Promise((rs, rj) => {
let count = 0
let result = []
const len = promises.length
if (len === 0) {
return resolve([])
}
promises.forEach((p, i) => {
Promise.resolve(p).then((res) => {
count += 1
result[ i ] = {
status: 'fulfilled',
value: res
}
if (count === len) {
rs(result)
}
}).catch((err) => {
count += 1
result[i] = {
status: 'rejected',
reason: err
}
if (count === len) {
rs(result)
}
})
})
})
}
const p1 = 1
const p2 = Promise.resolve(2)
const p3 = Promise.reject(3)
Promise.myAllSettled([ p1, p2, p3 ]).then(console.log)