-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path33.implement-Promise-allSettled.js
More file actions
48 lines (41 loc) · 1.17 KB
/
33.implement-Promise-allSettled.js
File metadata and controls
48 lines (41 loc) · 1.17 KB
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
/**
* @param {Array<any>} promises - notice that input might contains non-promises
* @return {Promise<Array<{status: 'fulfilled', value: any} | {status: 'rejected', reason: any}>>}
*/
function allSettled(promises) {
return new Promise(async (resolve) => {
const data = []
for (const p of promises) {
let res
try {
res = { status: 'fulfilled', value: await p }
} catch (e) {
res = { status: 'rejected', reason: e }
} finally {
data.push(res)
}
}
resolve(data)
})
}
function allSettled(promises) {
return new Promise((resolve) => {
const data = []
const iterator = promises[Symbol.iterator]()
function walk({ done, value }) {
if (done) {
return resolve(data)
}
if (Object.prototype.toString.call(value).slice(8, -1) !== 'Promise') {
data.push({ status: 'fulfilled', value })
walk(iterator.next())
} else {
value
.then((v) => data.push({ status: 'fulfilled', value: v }))
.catch((e) => data.push({ status: 'rejected', reason: e }))
.finally(() => walk(iterator.next()))
}
}
walk(iterator.next())
})
}