·vincent

网络请求并发限制的管理类

网络请求并发限制的管理类

Javascript

实现网络请求并发限制的管理类 NetManager(concurrency), 构造函数传入一个 number,是并发的限制数, 提供 request(url, data) => Promise 方法

js
1// 实现网络请求并发限制的管理类 NetManager(concurrency),
2// 构造函数传入一个number,是并发的限制数,
3// 提供 request(url, data) => Promise<res> 方法
4// Const obj = new NetManager(5)
5// obj.request(“/xxx/sss”, {a: 1})
6
7// net-manager.js
8class NetManager {
9  constructor(number) {
10    if (!(typeof number === 'number' && !Number.isNaN(number))) {
11      console.error(`NetManager params typeof number === '${typeof number}', value: ${number}`);
12    }
13
14    this.number = number;
15    this.queues = [];
16    this.caches = [];
17  }
18
19  trigger = () => {
20    const hits = this.queues.filter((i) => i.isFetch === false);
21    hits.forEach((item) => {
22      item.isFetch = true;
23
24      item
25        .task()
26        .then(item.resolve)
27        .catch(item.reject)
28        .finally(() => {
29          const deleteIndex = this.queues.findIndex((del) => del.key === item.key);
30
31          if (deleteIndex !== -1) {
32            this.queues.splice(deleteIndex, 1);
33          }
34
35          if (this.caches.length > 0) {
36            this.queues.push(this.caches.shift());
37            this.trigger();
38          }
39        });
40    });
41  };
42
43  request = (...reset) => {
44    return new Promise((resolve, reject) => {
45      // 绑定一个函数并传参
46      const task = window.fetch.bind(null, ...reset);
47
48      // 生成一个key值,用于删除队列任务
49      const key = Math.random();
50
51      const newItem = {key, isFetch: false, task, resolve, reject};
52      if (this.queues.length >= this.number || this.caches.length > 0) {
53        this.caches.push(newItem);
54      } else {
55        this.queues.push(newItem);
56        this.trigger();
57      }
58    });
59  };
60}
61const JSON_PLACEHOLDER = 'https://jsonplaceholder.typicode.com/todos/';
62
63const obj = new NetManager(2);
64
65for (let i = 1; i <= 10; i++) {
66  obj
67    .request(`${JSON_PLACEHOLDER}${i}`, {credentials: 'include'})
68    .then((res) => res.json())
69    .then((result) => {
70      console.log('result', result);
71    })
72    .catch((err) => {
73      console.error(err);
74    });
75}
76
77

相关知识

  • 队列任务

  • 批量任务、有规律、有逻辑的执行的时候需要用到

应用场景

1 批量文件上传 文件切片,批量图片上传(聊天)

2 多任务相互依赖 比如有三个请求,1、2 和 3,请求 2 依赖 1 3 依赖 2。

3 表单校验 多个异步校验表单

4 发送消息 保证消息发送顺序,接收顺序

5 计数器 聊天软件未读数、已读数、表情回复

6 http 并发请求限制