前端如何做异步并发量的控制?
程序员文章站
2022-03-30 09:53:13
利用promise,asyn等等这些都能控制并发请求量,话不多说,代码如下:完整代码以及测试用例: 异步函数 ...
利用promise,asyn等等这些都能控制并发请求量,话不多说,代码如下:
完整代码以及测试用例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>异步函数</title>
</head>
<body>
<script>
const mapLimit = (list, limit, asyncHandle) => {
const recursion = (arr) => {
return asyncHandle(arr.shift()).then((res) => {
console.log('data', res);
if (arr.length > 0) {
return recursion(arr)
}
return 'finish'
})
}
let asyncList = [];
let listCopy = [].concat(list);
while (limit--) {
asyncList.push(recursion(listCopy))
}
return Promise.all(asyncList);
}
var dataLists = [1,2,3,4,5,6,7,8,9,10];
var count = 0;
mapLimit(dataLists, 3, (curItem)=>{
return new Promise(resolve => {
count++
setTimeout(()=>{
console.log(curItem, '当前并发量:', count--)
resolve();
}, 1000)
});
}).then(response => {
console.log('finish', response)
});
</script>
</body>
</html>
本文地址:https://blog.csdn.net/qq_45065517/article/details/107223576