一次性强求很多和接口处理方法

import axios from 'axios'

export const handQueue = (
  reqs // 请求总数
) => {
  reqs = reqs || []


  const requestQueue = (concurrency) => {
    concurrency = concurrency || 6 // 最大并发数
    const queue = [] // 请求池
    let current = 0

    const dequeue = () => {
      while (current < concurrency && queue.length) {
        current++;
        const requestPromiseFactory = queue.shift() // 出列
        requestPromiseFactory()
          .then(() => { // 成功的请求逻辑
          })
          .catch(error => { // 失败
            console.log(error)
          })
          .finally(() => {
            current--
            dequeue()
          });
      }

    }

    return (requestPromiseFactory) => {
      queue.push(requestPromiseFactory) // 入队
      dequeue()
    }

  }

  const enqueue = requestQueue(6)

  for (let i = 0; i < reqs.length; i++) {

    enqueue(() => axios.get('/api/test' + i))
  }
}

转自面试官:假如有几十个请求,如何去控制并发? - 掘金 (juejin.cn)

posted @ 2024-07-19 17:24  心动12138  阅读(1)  评论(0编辑  收藏  举报