实现网络请求并发限制的管理类 NetManager(concurrency),构造函数传入一个number,是并发的限制数,提供 request(url, da
正文概述
掘金(大前端技术FE) 2020-12-18 500
代码实现
// 实现网络请求并发限制的管理类 NetManager(concurrency),构造函数传入一个number,是并发的限制数,提供 request(url, data) => Promise<res> 方法
// Const obj = new NetManager(5)
// obj.request(“/xxx/sss”, {a: 1})
class NetManager {
constructor(number) {
if (!(typeof number === 'number' && !Number.isNaN(number))) {
console.error(
`NetManager params typeof number === '${typeof number}', value: ${number}`
);
}
this.number = number;
this.queues = [];
this.caches = [];
}
trigger = () => {
const hits = this.queues.filter((i) => i.isFetch === false);
hits.forEach((item) => {
item.isFetch = true;
item.task()
.then(item.resolve)
.catch(item.reject)
.finally(() => {
const deleteIndex = this.queues.findIndex(
(del) => del.key === item.key
);
if (deleteIndex !== -1) {
this.queues.splice(deleteIndex, 1);
}
if (this.caches.length > 0) {
this.queues.push(this.caches.shift());
this.trigger();
}
});
});
};
request = (...reset) => {
return new Promise((resolve, reject) => {
// 绑定一个函数并传参
const task = window.fetch.bind(null, ...reset);
// 生成一个key值,用于删除队列任务
const key = Math.random();
const newItem = {key, isFetch: false, task, resolve, reject};
if (this.queues.length >= this.number) {
this.caches.push(newItem);
} else {
this.queues.push(newItem);
this.trigger();
}
});
};
}
const JSON_PLACEHOLDER = 'https://jsonplaceholder.typicode.com/todos/';
const obj = new NetManager(2);
for (let i = 1; i <= 10; i++) {
obj.request(`${JSON_PLACEHOLDER}${i}`, {credentials: 'include'})
.then((res) => res.json())
.then((result) => {
console.log('result', result);
});
}
执行结果
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!