-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise-allSettled.js
33 lines (28 loc) · 1.06 KB
/
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
Promise.customAllSettled = function(promises) {
return new Promise((resolve) => {
const results = []
let counter = 0
promises.forEach((promise, idx) => {
Promise
.resolve(promise)
.then(value => {
results[idx] = {status: 'fulfilled', value}
})
.catch(reason => {
results[idx] = {status: 'rejected', reason}
})
.finally(() => {
counter++
if (promises.length === counter) {
resolve(results)
}
})
})
})
}
const rs1 = () => new Promise(resolve => setTimeout(() => resolve(1), 300))
const rs2 = () => new Promise(resolve => setTimeout(() => resolve(2), 200))
const rj = () => new Promise((_, reject) => setTimeout(() => reject(3), 100))
Promise.customAllSettled([ rs1(), rs2(), rj()])
.then(result => console.log('runtime then', result))
.catch(err => console.error('runtime catch', err));