并发请求小练习

试图写的更简洁一点,然而水平有限

题干:

题干

解:

 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
/**
 * 限制并发数的请求
 * @param urls String[] 资源数组
 * @param max Number 最大并发数
 * @param callback Func 全部执行完毕后回调
 */
function concurFetch(urls, max, callback) {
  const isAllOfThem = urls.length === max
  const resultPromise = []
  const fetchPoor = urls.slice(0, max)
  const queue = urls.slice(max)
  const fetchPush = (url, cb) => {
    const promise = fetch(url)
    resultPromise.push(promise)
    promise.then(cb)
  }
  const checkAllComplete = () => Promise.all(resultPromise).then(callback)
  const recursion = () => {
    const nowLen = queue.length
    nowLen > 0 && fetchPush(queue.shift(), recursion)
    nowLen === 1 && checkAllComplete()
  }
  fetchPoor.forEach(item => {
    fetchPush(item, recursion)
  })
  isAllOfThem && checkAllComplete()
}

// 跑一下试试:
const fetch = () => {
  return new Promise((resolve, reject) => {
    window.setTimeout(() => {
      console.log("跑完了")
      resolve()
    }, 2000)
  })
}
const urls = Array(8).fill("someurl")
concurFetch(urls, 3, () => console.log("全部OK!"))

查下看有没有更骚的

Licensed under CC BY-NC-SA 4.0
Built with Hugo
主题 StackJimmy 设计