JS控制并发请求数量
作者:互联网
//链接 const arr_url = [ { url: 'url0', time: 3 }, { url: 'url1', time: 3 }, { url: 'url2', time: 3 }, { url: 'url3', time: 3 }, { url: 'url4', time: 3 }, { url: 'url5', time: 3 }, { url: 'url6', time: 0 }, { url: 'url7', time: 3 }, ]//请求 fetch fn const ajax = ({ url, time }) => { return new Promise((res, reject) => { setTimeout(() => { console.log(url); if (url == 'url3') { reject('失败了') } else {
res('成功了') } }, time * 1000) }) } //do fecth const getimg = arr => { const arr_result = [] const fetchall = async (idx) => { if (arr_result[idx]) { idx++ await fetchall(idx) } else { arr_result[idx] = 1 ajax(arr[idx]) .catch(r => console.log('Error', r)) .finally(r => { if (idx > arr.length) return idx++ if (arr[idx]) { fetchall(idx) } }) } } fetchall(0) //根据并发限制设定执行初始请求函数 fetchall(1) } getimg(arr)
ps:这是最终版本,最初的时候少个async和await,怎么弄都不对,后面查资料修改了,就没问题了,参考地址
标签:fetchall,arr,const,请求,idx,url,JS,并发,time 来源: https://www.cnblogs.com/Tomato-wang/p/16181267.html