支持promise的并发
# 工作场景
当处理多个请求的时候,如果同步地去处理,返回较慢,但是如果直接使用 Promise.all
又有可能导致阻塞,例如从 web worker
中传输数据到主线程,如果传输的数据过大,主线程会阻塞,导致页面卡死,于是可以将大数据拆分成多个小数据,并封装 Promise
实现并发处理
# (本人采取的方案)一次性导入,类 Promise.all
的处理方式
function schedulePromise(tasks, limit) {
const results = [];
let count = 0;
return new Promise((resolve, reject) => {
const run = () => {
if (count >= tasks.length) {
resolve(results);
return;
}
const task = tasks[count];
count++;
task()
.then((result) => {
results.push(result);
run();
})
.catch((error) => {
reject(error);
});
};
for (let i = 0; i < limit; i++) {
run();
}
});
}
// 使用示例
const tasks = [
() => new Promise((resolve) => setTimeout(() => resolve('Task 1'), 1000)),
() => new Promise((resolve) => setTimeout(() => resolve('Task 2'), 2000)),
() => new Promise((resolve) => setTimeout(() => resolve('Task 3'), 3000)),
];
schedulePromise(tasks, 2)
.then((results) => {
console.log(results);
// 输出: ['Task 1', 'Task 2', 'Task 3']
})
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
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
# p-queue
使用成熟的第三方库 p-queue
实现并发处理
const pQueue = new PQueue({ concurrency: 2 });
const tasks = [
() => new Promise((resolve) => setTimeout(() => resolve('Task 1'), 1000)),
() => new Promise((resolve) => setTimeout(() => resolve('Task 2'), 2000)),
() => new Promise((resolve) => setTimeout(() => resolve('Task 3'), 3000)),
];
const results = await Promise.all(tasks.map((task) => pQueue.add(task)));
console.log(results);
// 输出: ['Task 1', 'Task 2', 'Task 3']
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 参考
最近更新~: 2024/08/19, 01:05:55