-
Notifications
You must be signed in to change notification settings - Fork 108
/
promise-limit.js
84 lines (66 loc) · 1.55 KB
/
promise-limit.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
// 实现一个并发限制功能
function pLimit(arr, limit, callback) {
const promises = [];
const executing = [];
let index = 0;
const enquene = () => {
if (index === arr.length) {
return Promise.resolve();
}
const item = arr[index++];
const p = Promise.resolve().then(() => {
return callback && callback(item, arr);
});
promises.push(p);
const e = p.then(() => {
const exeIndex = executing.indexOf(e);
exeIndex > -1
? executing.splice(exeIndex, 1)
: Promise.resolve();
});
executing.push(e);
let r = Promise.resolve()
if (executing.length >= limit) {
r = Promise.race(executing);
}
return r.then(() => enquene());
};
return enquene().then(() => Promise.all(promises));
}
// test
const timeout = ms => new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, ms);
});
const ajax1 = () => timeout(5000).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;
});
const ajax4 = () => timeout(6000).then(() => {
console.log('4');
return 4;
});
const ajax5 = () => timeout(2000).then(() => {
console.log('5');
return 5;
});
const ajax6 = () => timeout(2000).then(() => {
console.log('6');
return 6;
});
pLimit(
[ajax1, ajax2, ajax3, ajax4, ajax5, ajax6],
3,
(item) => {
item();
}
);