异步控制

异步并行

异步串行

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
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;
});

function mergePromise(arr) {
const ret = [];

return new Promise((resolve, reject) => {
arr.reduce((pre, cur) => {
return pre.then(cur).then(res => {
ret.push(res);
if (ret.length === arr.length) {
resolve(ret)
}
});
}, Promise.resolve());
})
}

mergePromise([ajax1, ajax2, ajax3]).then(data => {
console.log('done');
console.log(data); // data 为 [1, 2, 3]
});


异步控制
https://mingmingjiang1.github.io/emocoder/2024/06/23/FE/并发和串行控制/
作者
迷途知返
发布于
2024年6月23日
许可协议