-
Notifications
You must be signed in to change notification settings - Fork 72
/
promiseAll.js
59 lines (57 loc) · 1.33 KB
/
promiseAll.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
function isPromise(obj) {
return (
!!obj && (typeof obj === 'function' || typeof obj === 'object') && typeof obj.then == 'function'
);
}
function isPromise(object) {
return (
!!object && (typeof obj === 'function' || typeof obj === 'object') && object instanceof Promise
);
}
function PromiseAll(arr) {
return new Promise((resolve, reject) => {
const len = arr.length,
result = [];
let succeed = 0;
for (let i = 0; i < len; ++i) {
const cur = arr[i];
if (isPromise(cur)) {
arr[i].then((res) => {
process(i, res);
}, reject);
} else {
process(i, cur);
}
}
function process(index, value) {
result[index] = value;
if (++succeed === len) {
resolve(result);
}
}
});
}
function myPromiseAll(arr) {
let res = [];
let containPromise = false;
return new Promise((resolve, reject) => {
for (let i = 0; i < arr.length; i++) {
if (isPromise(arr[i])) {
containPromise = true;
arr[i]
.then((data) => {
res[i] = data;
if (res.length === arr.length) {
resolve(res);
}
})
.catch((error) => {
reject(error);
});
} else {
res[i] = arr[i];
}
}
if (!containPromise) resolve(res);
});
}