js 併發

howhy發表於2024-08-02
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)
    })

相關文章