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

How to make a List in CocosCreator

CocosCreator version: 2.3.4 Cocos does not have a...

Analysis of pitfalls in rounding operation of ROUND function in MySQL

This article uses examples to illustrate the pitf...

MySQL tutorial DML data manipulation language example detailed explanation

Table of contents 1. Data Manipulation Language (...

MySql5.7.21 installation points record notes

The downloaded version is the Zip decompression v...

jQuery plugin to implement minesweeper game (3)

This article shares the third article on how to u...

Implementation of CSS circular hollowing (coupon background image)

This article mainly introduces CSS circular hollo...

Linux operation and maintenance basic swap partition and lvm management tutorial

Table of contents 1. Swap partition SWAP 1.1 Crea...

Detailed explanation of MySQL from getting started to giving up - installation

What you will learn 1. Software installation and ...

How to query whether the mysql table is locked

Specific method: (Recommended tutorial: MySQL dat...

How to migrate mysql storage location to a new disk

1. Prepare a new disk and format it with the same...

Linux Check the installation location of the software simple method

1. Check the software installation path: There is...

Vue achieves seamless carousel effect

This article shares the specific code of Vue to a...

vite2.x implements on-demand loading of ant-design-vue@next components

1. Use version vite:2.0 ant-design-vue: 2.0.0-rc....