js 并发

function concurRequest(maxnum) {
      return new Promise((resolve, reject) => {
        let index = 0
        let count = 0
        const results = []
        async function request() {
          const i = index
          const url = urls[index]
          index++
          try {
            const resp = await fetch(url)
            results[i] = resp
          } catch (err) {
            results[i] = err
          } finally {
            count++
            if (count === urls.length) {
              resolve(results)
            }
            if (index < urls.length) {
              request()
            }
          }

        }
        for (let i = 0; i < maxnum; i++) {
          request()
        }
      })
    }
    concurRequest(3).then(res => {
      console.log(res)
    })

 

posted @ 2024-08-02 11:34  howhy  阅读(2)  评论(0编辑  收藏  举报