PrefaceTo be honest, I've been feeling very confused recently. About technology and life. I also talked to many friends in large companies, hoping to get some ideas for future development. We also talked about interviews and some of the questions that will be asked to interviewees during recruitment. It just so happened that I hadn't had an interview for a long time, so I chose a few from them. A series of analyses of some interview questions will be released soon. Today’s one is from ByteDance: Implement a batch request function multiRequest(urls, maxNum) with the following requirements: • Requires the maximum number of concurrent connections maxNum • Every time a request is returned, a slot is left open for a new request to be added • After all requests are completed, the results are printed out in the order of the urls I think many students have seen this question to some extent. Below I will go through the scenario, problem analysis and final implementation step by step, and try to give a complete analysis of this question in a simple and easy-to-understand way. ScenarioSuppose there is such a scenario: there are 30 asynchronous requests that need to be sent, but for some reason, we must control the number of concurrent requests at the same time to less than 5, and get the response results as quickly as possible. What should be done? First, let's take a look at the serial and parallel nature of Ajax. Implementing serial and parallel Ajax based on Promise.allWe usually encapsulate asynchronous requests based on promise, and here we mainly focus on asynchronous requests.
By defining some promise instances to specifically demonstrate serial/parallel. Serial var p = function () { return new Promise(function (resolve, reject) { setTimeout(() => { console.log("1000"); resolve(); }, 1000); }); }; var p1 = function () { return new Promise(function (resolve, reject) { setTimeout(() => { console.log("2000"); resolve(); }, 2000); }); }; var p2 = function () { return new Promise(function (resolve, reject) { setTimeout(() => { console.log("3000"); resolve(); }, 3000); }); }; p() .then(() => { return p1(); }) .then(() => { return p2(); }) .then(() => { console.log("end"); }); As shown in the example, the serial will execute the corresponding interface requests from top to bottom. parallel Usually, when we need to ensure that the code is executed after multiple asynchronous processes, we will use: Promise.all((promises: [])).then((fun: function)); Promise.all can ensure that all promise objects in the promises array reach the resolved state before executing the then callback. var promises = function () { return [1000, 2000, 3000].map((current) => { return new Promise(function (resolve, reject) { setTimeout(() => { console.log(current); }, current); }); }); }; Promise.all(promises()).then(() => { console.log("end"); }); Promise.all concurrency limitConsider a scenario at this time: if each object in your promises array is an http request, and there are hundreds of thousands of such objects. What will happen is that you send hundreds of thousands of http requests in an instant, which is likely to lead to the accumulation of countless call stacks and memory overflow. At this time, we need to consider concurrency restrictions on Promise.all. The concurrency limit of Promise.all means that the number of promises executed concurrently at each moment is fixed, and the final execution result remains consistent with the original Promise.all. Title Implementation Thought Analysis The whole process is implemented using recursive calls: the number of requests initially sent is capped at the maximum allowed, and each of these requests should continue to be sent recursively upon completion, with the specific URL in urls determined by the passed index to ensure that the final output order is not messed up, but is output sequentially. Code Implementation function multiRequest(urls = [], maxNum) { //Total number of requests const len = urls.length; // Create an array to save the request results based on the number of requests const result = new Array(len).fill(false); // Current completed number let count = 0; return new Promise((resolve, reject) => { // Request maxNum while (count < maxNum) { next(); } function next() { let current = count++; // Handle boundary conditions if (current >= len) { // Once all requests are completed, set the promise to a successful state, and then return result as the promise value!result.includes(false) && resolve(result); return; } const url = urls[current]; console.log(`start ${current}`, new Date().toLocaleString()); fetch(url) .then((res) => { // Save request result result[current] = res; console.log(`Completed${current}`, new Date().toLocaleString()); // If the request is not completed, recurse if (current < len) { next(); } }) .catch((err) => { console.log(`end ${current}`, new Date().toLocaleString()); result[current] = err; // If the request is not completed, recurse if (current < len) { next(); } }); } }); } SummarizeThis is the end of this article about ByteDance interview on how to use JS to implement Ajax concurrent request control. For more relevant JS implementation of Ajax concurrent request control content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: How to configure ssh to log in to Linux using git bash
>>: Solution to the problem that the mysql8.0.11 client cannot log in
Introduction When the MySQL InnoDB engine queries...
Table of contents Overview Code Implementation Su...
Table of contents Global Registration Partial Reg...
The biggest bottleneck of using zabbix is the d...
Preface During the development process, we someti...
Step 1: Install Stow In this example, we are usin...
Summarize Global environment ➡️ window Normal fun...
Vue encapsulates the breadcrumb component for you...
Table of contents What is a skeleton screen How t...
In our life, work and study, social networks have ...
Enable remote access rights for mysql By default,...
1. Download MySQL URL: https://dev.mysql.com/down...
This article example shares the specific code of ...
Preface: One day, I built a MySQL service in Dock...
background This article mainly tests whether the ...