url并发请求

    function batchRequest(urls,maxNum){
      return new Promise(resolve=>{
        if(urls.length===0){
          resolve([]);
          return;
        }
        const results=[];
        let index=0;
        let finishCount=0;
        async function urlRequest(){
          if(index===urls.length){
            return;
          }
          const retInd=index;
          const url=urls[index];
          index++;
          try{
          const resp=await fetch(url);
          results[retInd]=resp
          }catch(err){
            results[retInd]=err;
          }finally{
            finishCount++;
            if(finishCount===urls.length){
              resolve(results);
            }
            urlRequest()
          }
        }
        const forCount=Math.min(maxNum,urls.length);
        for(let i=0;i<forCount;i++){
          urlRequest();
        }
      })
    }

 

posted @ 2024-05-16 17:50  howhy  阅读(4)  评论(0编辑  收藏  举报