ByteDance interview: How to use JS to implement Ajax concurrent request control

ByteDance interview: How to use JS to implement Ajax concurrent request control

Preface

To 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.

Scenario

Suppose 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.all

We usually encapsulate asynchronous requests based on promise, and here we mainly focus on asynchronous requests.

  • Serial: After one asynchronous request is completed, the next request is made
  • Parallelism: multiple asynchronous requests are processed simultaneously

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 limit

Consider 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();
          }
        });
    }
  });
}

Summarize

This 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 use Promise in JavaScript to control the number of concurrent requests
  • Example code for implementing concurrent request control in JavaScript/TypeScript
  • Example code for implementing concurrency control using JavaScript
  • Example of method for controlling concurrent number of js asynchronous interfaces
  • Nodejs crawler advanced tutorial asynchronous concurrency control
  • Nodejs practical experience: eventproxy module to control concurrency
  • How to implement concurrency control in JavaScript

<<:  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

Recommend

Example of converting webpack images to base64

Download url-loader yarn add -D url-loader module...

MySQL 8.0.18 stable version released! Hash Join is here as expected

MySQL 8.0.18 stable version (GA) was officially r...

CSS to achieve dynamic secondary menu

Dynamically implement a simple secondary menu Whe...

Difference between HTML ReadOnly and Enabled

The TextBox with the ReadOnly attribute will be di...

html option disable select select disable option example

Copy code The code is as follows: <select> ...

Example code for implementing random roll caller in html

After this roll call device starts calling the ro...

Vue event's $event parameter = event value case

template <el-table :data="dataList"&...

Detailed explanation of the usage and difference between nohup and & in Linux

Example: We use the Python code loop_hello.py as ...

How to change $ to # in Linux

In this system, the # sign represents the root us...

Looping methods and various traversal methods in js

Table of contents for loop While Loop do-while lo...

Vue interpretation of responsive principle source code analysis

Table of contents initialization initState() init...

How to implement digital paging effect code and steps in CSS

A considerable number of websites use digital pagi...

Vue implements online preview of PDF files (using pdf.js/iframe/embed)

Preface I am currently working on a high-quality ...