题目:请实现如下函数,可以批量请求数据。所有的url地址都在urls参数中,同时可以通过max控制请求的并发度,当所有请求结束后,调用callback回调函数。请求直接用fetch就可以。
直接上代码:
var urls = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
const limit = 5;
// 主函数
function sendRequest(urls, limit , callback) {
function _send (urls) {
return fetch(urls.shift())
.finally(() => {
if(urls.length) {
return _send(urls)
}
})
}
let asyncList = [];
while(limit--) {
asyncList.push(_send(urls));
}
return Promise.all(asyncList).then(callback);
}
sendRequest(urls, limit, function() {
console.log('finish')
});
用setTimeout改写后测试一波,如下:
var urls = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
const limit = 5;
function sendRequest(urls, limit , callback) {
function _send (urls) {
const url = urls.shift();
if(url) {
return new Promise((resolve, reject) => {
setTimeout(()=>{
console.log(`当前发送:${url}`);
resolve(url);
}, 10)
})
.finally(() => {
if(urls.length > 0) {
return _send(urls)
}
})
}
}
let asyncList = [];
while(limit--) {
asyncList.push(_send(urls));
}
return Promise.all(asyncList).then(callback);
}
sendRequest(urls, limit, function() {
console.log('all urls sended!')
});
Nodejs输入一波结果:
➜ Desktop node 1.js
当前发送:1
当前发送:2
当前发送:3
当前发送:4
当前发送:5
当前发送:6
当前发送:7
当前发送:8
当前发送:9
当前发送:10
当前发送:11
当前发送:12
当前发送:13
当前发送:14
当前发送:15
当前发送:16
当前发送:17
当前发送:18
当前发送:19
当前发送:20
all urls sended!
➜ Desktop