如果有一百个接口需要请求,如何在最短时间内请求完毕(同一时间内请求数量不能超过五个)

之前面试前端的时候遇到的一个问题,题目内容就是上面说的,有什么好的思路呢?

阅读 3.3k
1 个回答
count = 0;
function send(){
    if(count < 5){
        count++;
        // 发送
    }
    send();
}
function finallyCallback(){
    count--;
    send();
}
send();

大概就是如上代码吧。


count = 0;
function send(){
    if(count < 5){
        count++;
        if(list.length){
            
            // 发送
            ajaxSend(list.shift());
            send();
        }
    }
    
}
function finallyCallback(){
    console.log(Date.now(), 'finallyCallback')
    count--;
    send();
}

function ajaxSend(data){
    console.log(Date.now(), 'ajaxSend', data)
    const xhr = new XMLHttpRequest();
    xhr.open(data.method || 'get', data.url)
    xhr.send();
    xhr.onload = xhr.onerror = finallyCallback;
}


list = Array.from({length: 100}).map((v,i)=>({url: `https://www.lilnong.top/cors/${i}`}));
send();

补全一下代码,在控制台就能看

count = 0;
function send(){
    if(count < 5){
        count++;
        if(list.length){
            
            // 发送
            ajaxSend(list.shift());
            send();
        }
    }
    
}
function finallyCallback(){
    console.log(Date.now(), 'finallyCallback')
    count--;
    send();
}

function ajaxSend(data){
    console.log(Date.now(), 'ajaxSend', data)
    fetch(data.url, data).then(v=>v.text()).catch(e=>e).then(finallyCallback)
}


list = Array.from({length: 100}).map((v,i)=>({url: `https://www.lilnong.top/cors/${i}`}));
send();

实现了一个 fetch 的。看你熟悉那个 api。 再贴个日志图。

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题