当前位置: 首页 > 后端技术 > Node.js

Node的请求管理器

时间:2023-04-03 23:12:31 Node.js

当同时发起很多请求时,会严重降低每个请求的响应速度,或者导致接口请求失败,所以需要控制并发请求数。createRequestManage函数可以创建一个全局请求管理器。管理请求。当请求超过上限时,请求将被放入队列。functioncreateRequestManage(limit){letcurrentTotal=0lettodoList=[]return{schedule(callback){if(currentTotal>limit){todoList.push(callback)}else{currentTotal++letnext=()=>{currentTotal--if(todoList.length>0){letcb=todoList.shift()cb().finally(next)}}callback().finally(next)}}}}使用方法:constrequestManage=createRequestManage(500)请求.schedule(()=>{axios.get('').then(res=>{})})