背景
有的时候后端提供的接口对相同的IP进行限制,在某个时间内不能发送超过X条的请求,一旦超过指定的请求数会导致后续请求接口会出现异常。
效果
需求
比如:在1s内最多同时发送2个请求,多出来的请求在后续的1s或者后续的Ns中发起
代码
<template>
<div class="app">
<el-divider content-position="center"
>1.1s内向某个IP最多发送2个请求</el-divider
>
<el-button type="primary" @click="send_request">发送请求</el-button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {}
},
methods: {
send_request() {
// 需要发送的请求个数
const need_send_request_num = 5
const queue_arr = []
/**
*
* @param total_request_num 需要向服务请求的总数
* @param max_request_num 向某个IP最大请求数量
* @param startIndex 第N个请求
*/
const foo = (total_request_num, max_request_num = 2, startIndex = 0) => {
if (startIndex >= total_request_num) {
// console.log('所有请求完成了')
// TODO:所有请求完成时
Promise.all(queue_arr).then((res) => {
console.log(res)
})
} else {
const endIndex =
startIndex + max_request_num > total_request_num
? total_request_num
: startIndex + max_request_num
let i = startIndex
for (; i < endIndex; i++) {
queue_arr.push(this.fetchData(i))
}
setTimeout(() => {
foo(total_request_num, max_request_num, i)
}, 1000)
}
}
foo(need_send_request_num)
},
async fetchData(index) {
const res = await axios.get('https://httpbin.org/get', {
params: {
index,
},
})
return res.data
},
},
}
</script>
<style lang="less" scoped>
.app {
padding: 40px;
}
</style>
标签:1s,const,请求,request,次数,startIndex,num,total
From: https://www.cnblogs.com/it774274680/p/18282640