preface

Recently in the development of the project summary meeting, the boss proposed that the project for the first time into the card, resulting in user feedback is not very ideal, we are very serious back to the sentence, the page interface is too much, a lot of interface waiting for the request of bala bala some.

Here’s what happened:

When I got back to my seat, I wondered if I could limit the number of interface requests. There were similar interview questions and discussions online, so I looked them up and summarized them myself.

Train of thought to understand

Train of thought

In fact, this problem seems to be quite complicated, if you think about it, in fact, from the outside of the promise and Max, and then loop through the list of requests, determine if it is equal to Max, if it is equal to, wait for the list of requests to complete, if not, put a new request into the list of requests

process

  • According to themaxValue to create a new request arrayrequestArr(length Max) or pass in an array containing multiple requests, and pass in themaxCut the length of a new array
  • willrequestArrItems are thrown into a loop (recursive implementation) and then deleted
  • Judge after executionrequestArrWhether the length reachesmaxUpper limit, if the array has reached the length of the upper limit, then continue to execute the loop, if there is space to determine whether there is still a request not added to the request list, if so, add to the request data list and then execute

code

let requestList = (urls = [], Limit = 5) = > {/ / whether urls, and null if not (urls. Length = = = 0 | | urls = = = null) {return false} / / deep copy a urls, circulation with the let urlsCopy = urls.slice(0) let requestArr = [] if (urls.length < limit) { requestArr = urlsCopy } else { requestArr = urlsCopy.splice(0, Max)} // Write a recursive loop request const call = () => {// Get the currently triggered request let a = promise.race (requestArr) // The current request triggers whether it fails or succeeds A.resolve (resolve).catch(reject).finally(() => {// Delete requestarr.foreach (item => { requestArr.splice(requestArr.indexOf(a), If (urlsCopy. Length) {if (urlsCopy. Length) {if (urlsCopy. Length) Requestarr.push (urlretroretro.shift ()) call()} if (requestarr.length) {call()}}Copy the code

Above is a simple request, without thinking too much, write it out first to see if you can limit it and see how it works

The above function

Subsequent thinking

After the recent example above, it seems that it is not very practical for the project. Can you wrap the AXIos request get and POST methods in one place

Refer to the connection

How does JS limit the number of “concurrent” promises: