-
Notifications
You must be signed in to change notification settings - Fork 181
/
9.promise.all.js
106 lines (88 loc) · 2.13 KB
/
9.promise.all.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
96
97
98
99
100
101
102
103
104
105
106
Promise.myAll = (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 ] = res
if (count === len) {
rs(result)
}
}).catch(rj)
})
})
}
Promise.myAll2 = (promises) => {
return new Promise((resolve, reject) => {
if (!Array.isArray(promises)) {
return reject('Promise.all accepts an array')
}
const length = promises.length
let remaining = length
const result = []
if (length === 0) {
return resolve([])
}
const response = (i, value) => {
try {
if (value instanceof Promise) {
// 注意此val非value
value.then((val) => {
response(i, val)
}, reject)
return
}
result[ i ] = value
if (--remaining === 0) {
resolve(result)
}
} catch (err) {
reject(err)
}
}
for (let i = 0; i < length; i++) {
response(i, promises[i])
}
})
}
let p1 = Promise.resolve(1);
let p2 = 2;
let p3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 3);
});
let p4 = Promise.reject('出错啦')
// Promise.myAll([ p1, p2, p3 ]).then((res) => {
// console.log(res, 'res---1')
// }).catch((err) => {
// console.log('err', err)
// })
// Promise.myAll([ p1, p2, 3 ]).then((res) => {
// console.log(res, 'res---2')
// }).catch((err) => {
// console.log('err', err)
// })
// Promise.myAll([ p1, p2, p4 ]).then((res) => {
// console.log(res, 'res--3')
// }).catch((err) => {
// console.log('err', err)
// })
// Promise.myAll2([ p1, p2, p3 ]).then((res) => {
// console.log(res, 'res---1')
// }).catch((err) => {
// console.log('err', err)
// })
// Promise.myAll2([ p1, p2, 3 ]).then((res) => {
// console.log(res, 'res---2')
// }).catch((err) => {
// console.log('err', err)
// })
Promise.myAll2([ p1, p2, p4 ]).then((res) => {
console.log(res, 'res--3')
}).catch((err) => {
console.log('err', err)
})