記一道控制并發(fā)數(shù)的前端面試題【手動維護 HTTP 請求排隊】
題目
原文來自掘金https://juejin.im/post/5c88aaa05188257e1f2925a8, 只是記錄一下自己的寫法, 據(jù)說是頭條的
image
function sendRequest(urls, max, callback) {
const url_queue = urls.slice();
?
return {
push(url) {
url_queue.push(url);
this.send();
},
send() {
if (url_queue.length === 0) {
callback();
}
console.log('send');
const handle_url_queue = url_queue.slice(0, max);
const handle_length = handle_url_queue.length;
let i = handle_length;
if (handle_length) {
handle_url_queue.forEach((url) => {
fetch(url)
.then(() => {
i--;
if (i === 0) {
url_queue.splice(0, handle_length);
if (url_queue.length === 0) {
callback();
} else {
this.send();
}
}
})
})
}
}
}
}
我這個似乎不特別的符合題意...還需要調(diào)用返回的 send 方法, 不過這確實是我下意識第一反應了
保存一個不被污染的隊列, 不就是閉包嗎?!