优化接口请求的数量

如果请求的数量很多,可以将其收集合并,从而减少接口调用的数量

每次请求从原来调用接口改为调collector方法,该方法返回promise,将promise的resolve注册到事件中。在时间窗口内的所有请求的参数会被收集。

在截流函数中发起真正的请求,请求结束后消费掉事件,也会触发promise的resolve。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { throttle } from 'lodash';

export default class PatchMatch {
  private constructor() {
    this.bus = new EventBus();
  }

  public collector = (id, param) => {
    this.params.push(param);
    this.runner();
    return new Promise((resolve, reject) => {
      this.bus.on(id, resolve);
    });
  };

  private bus: EventBus;

  private params: any[] = [];

  private runner = throttle(() => {
    this.doPatchMatch();
    this.params = [];
  }, 100);

  private doPatchMatch = () => {
    fetch(`${urls.bizFormExtra.patchMatch}`, this.params).then(result => {
      const budgetAccountItems: Array<any> = result.data.data.itemBudgetAccounts;
      budgetAccountItems.forEach(bItem => {
        this.bus.emit(bItem.itemId, bItem);
      });
    });
  };
}

class EventBus {
  public on = (eventName, callback) => {
    this.eventMap[eventName] = callback;
  };
  private eventMap: { [key: string]: Function } = {};
  public emit = (eventName, ...args) => {
    const callback = this.eventMap[eventName];
    if (callback) {
      callback(...args);
      this.eventMap[eventName] = undefined
    }
  };
}
updatedupdated2024-03-232024-03-23