# 批量请求--控制并发数

# 功能实现是:同时最多请求5个,回来一个后取队列的下一个,直到全部完成。

FetchLimit.js

主体实现代码:

// paramsList 是参数的数组
this.requestHandle(paramsList)

requestHandle(list) {
        const _that = this
        this.currentTotal = list.length

        function requestBody(args) {
          const params = args[0]
          const currentLine = args[1] + 3
          const {
            sn
          } = params

          return new Promise(resolve => {
            _that.$http.post('/api/device/addDevice', params).then(res => {
              if (res.status == 200) {
                _that.addSuccessCount += 1
              } else {
                _that.showError(res.status, sn, currentLine);
              }
              resolve(res)
            })
          });
        }

        let promises = [];
        const requestInstance = new FetchLimit(5);// 最多同时请求5个

        function send() {
          for (let i = 0; i < list.length; i++) {
            promises.push(
              requestInstance
              .request(requestBody, list[i], i)
              .then(
                result => {
                  _that.currentIndex = i + 1
                  _that.calcProgress()
                  console.log('result', i, result)
                },
                error => console.log(error),
              ),
            );
          }
        }
        send();
      },