Parallel requests

  • Promise. All methods

    (async() = > {const [data1, data2, data3] = await Promise.all([
        Promise.resolve(1),
        Promise.resolve(2),
        Promise.resolve(3),
      ])
      .catch(e= > {
        console.error(e)
      })
      console.log(`Received data: ${data1}`)
      console.log(`Received data: ${data2}`)
      console.log(`Received data: ${data3}`)
    })()
    Copy the code

    If one of the asynchronous tasks fails, all tasks are suspended and the Promise goes to the Rejected state

  • Promise. AllSettled method

    (async() = > {const response = await Promise.allSettled([
        Promise.reject(1),
        Promise.resolve(2),
        Promise.resolve(3),])console.log('Received data:', response)
    })()
    Copy the code
    [{"status": "rejected"."reason": 1 },
      { "status": "fulfilled"."value": 2 },
      { "status": "fulfilled"."value": 3},]Copy the code

    Success or exception will return the corresponding state, and the developer will filter the desired result based on the business

  • Usage scenarios

    Send all requests all at once and wait for all the results to be received

    This is ideal for situations where the number of requests is fixed and asynchronous tasks do not need to be executed in the expected order

Serial requests

  • For – loops

    (async() = > {const promises = [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]
      for (const [index, promise] of promises.entries()) {
        console.log(`Received data: The ${await promise}`)}console.log('Finished')
    })()
    Copy the code
  • Asynchronous traverser

    (async() = > {const promises = [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]
      try {
        for await (const data of promises) {
          console.log('Received data:', data)
        }
      } catch (e) {
        console.error(e)
      }
      console.log('Finished')
    })()
    Copy the code
  • Usage scenarios

    Execute the asynchronous tasks in the expected order, i.e. wait for the previous await to complete before executing the next await

    This is ideal for situations where the number of requests is fixed and asynchronous tasks need to be executed in the expected order

Control the number of concurrent requests

  • Chrome request mechanism

    A maximum of six TCP connections can be established for a domain name. That is, the maximum number of concurrent connections for a domain name is 6

    If the number of concurrent requests reaches a certain level, it is possible to run out of memory by piling up countless call stacks

  • Implementation approach

    Concurrency is achieved through a while loop

    Control the number of requests through recursion

  • Take the batch download of files as an example

    const invariable = ({ list = [], limit = 4, complete = () => {} }) = > {
      return new Promise((resolve, reject) = > {
        let count = 0, total = list.length
        const recursion = (url, data) = > {
          fetchFileStream(url).then(blob= > {
            complete({ data, response: blob })
            count += 1
            if (list.length) {
              const { url, data } = list.shift()
              recursion(url, data)
            } else {
              count === total && resolve('finish')
            }
          })
        }
        limit = total > limit ? limit : total
        while(limit--) {
          const { url, data } = list.shift()
          recursion(url, data)
        }
      })
    }
    Copy the code