-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromiseMerge.ts
64 lines (54 loc) · 1.31 KB
/
promiseMerge.ts
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
const timeout = ms => new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, ms);
});
const ajax1 = () => timeout(2000).then(() => {
console.log('1');
return 1;
});
const ajax2 = () => timeout(1000).then(() => {
console.log('2');
return 2;
});
const ajax3 = () => timeout(2000).then(() => {
console.log('3');
return 3;
});
let data = [];
let ajaxArray = [ajax1, ajax2, ajax3];
ajax1().then(num => {
data.push(num);
ajax2().then(num => {
data.push(num);
ajax3().then(num => {
data.push(num);
}).then(num => {
console.log(data);
});
})
});
const _mergePromise = async (array) => {
let results = [];
for (let i = 0; i < array.length; i++) {
let r = await array[i]();
results.push(r);
}
return results; // will be resolved value of promise
};
const mergePromise = ajaxArray => {
let data = [];
const processOne = (ajax) => {
return ajax().then((num) => {
data.push(num);
});
};
ajaxArray.map(ajax => processOne(ajax));
// return data;
console.log(data);
};
mergePromise([ajax1, ajax2, ajax3]);
// mergePromise([ajax1, ajax2, ajax3]).then(data => {
// console.log('done');
// console.log(data); // data 为 [1, 2, 3]
// });