-
Notifications
You must be signed in to change notification settings - Fork 1
/
limitParallelAsync.js
87 lines (71 loc) · 1.68 KB
/
limitParallelAsync.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
// 并行限制请求
const limitParallelAsync = (limit) => {
const queue = []
let activeCount = 0
const next = () => {
activeCount--
if (queue.length) {
queue.shift()()
}
}
return (fn) => new Promise((resolve,reject) => {
const run = () => {
activeCount++
fn().then((rs)=>{
resolve(rs)
next()
}, err => {
reject(rs)
next()
})
}
if (activeCount < limit) {
run()
} else {
queue.push(run)
}
})
}
const collectPromise = limitParallelAsync(2)
const fakeAsync = (timer, type) => {
return () => new Promise((resolve) => {
setTimeout(() => {
console.log(`${timer}---${type}`)
resolve(`${timer}---${type}`)
}, timer)
})
}
const arr = [
collectPromise(fakeAsync(500, 'first')),
collectPromise(fakeAsync(1000, 'second')),
collectPromise(fakeAsync(2000, 'third')),
collectPromise(fakeAsync(2000, 'fourth')),
collectPromise(fakeAsync(1000, 'five')),
collectPromise(fakeAsync(1000, 'five1')),
collectPromise(fakeAsync(3000, 'five2')),
collectPromise(fakeAsync(3000, 'five3')),
]
Promise.all(arr).then(rs => {
console.log(rs)
})
// 是否正在刷新的标记
let isRefreshing = false
//重试队列
let requests = []
export function runPromise(fn) {
if (!isRefreshing) {
isRefreshing = true
requests.push(fn)
//调用刷新token的接口
refreshToken().then(res => {
// token 刷新后将数组的方法重新执行
requests.forEach((cb) => cb())
requests = [] // 重新请求完清空
isRefreshing = false
}).catch(_ => {
isRefreshing = false
})
} else {
requests.push(fn)
}
}