Promise控制网络请求数

71 阅读1分钟

控制网络请求数

/**
 * 限制请求
 * @param {Array} arrRequest 网络请求数组
 * @param {number} limit 允许一次性发几个请求
 * @param {Function} [handler] 自定义限制函数 - 可选
 * @returns {any}
 */
function limitNetworkRequest(arrRequest, limit, handler) {
  //原始队列
  const queueAll = Array.from(arrRequest);
  //提取后的数组
  const selectQueueOfIndex = queueAll.slice(0, limit).map((req, index) => {
    return handler(req).then(() => index);
  });

  return queueAll
    .reduce((preReq, currentReq) => {
      return preReq
        .then((promise) => {
          return Promise.race(selectQueueOfIndex);
        })
        .then((index) => {
          return (selectQueueOfIndex[index] = handler(currentReq).then(
            () => index
          ));
        })
        .catch((err) => console.error(err));
    }, Promise.resolve())
    //最后是判断是否全部o了
    .then(Promise.all(queueAll));
}