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

MySQL table return causes index invalidation case explanation

Introduction When the MySQL InnoDB engine queries...

JavaScript design pattern learning adapter pattern

Table of contents Overview Code Implementation Su...

How to automatically import Vue components on demand

Table of contents Global Registration Partial Reg...

Mysql optimization Zabbix partition optimization

The biggest bottleneck of using zabbix is ​​the d...

js uses cookies to remember user page operations

Preface During the development process, we someti...

How to Easily Remove Source Installed Packages in Linux

Step 1: Install Stow In this example, we are usin...

Detailed explanation of the this pointing problem in JavaScript

Summarize Global environment ➡️ window Normal fun...

Encapsulation method of Vue breadcrumbs component

Vue encapsulates the breadcrumb component for you...

Example of implementing the skeleton screen of WeChat applet

Table of contents What is a skeleton screen How t...

Comparative Analysis of UI Applications of Image Social Networking Sites (Figure)

In our life, work and study, social networks have ...

How to modify mysql permissions to allow hosts to access

Enable remote access rights for mysql By default,...

Detailed tutorial on installing Mysql5.7.19 on Centos7 under Linux

1. Download MySQL URL: https://dev.mysql.com/down...

Detailed explanation of jquery tag selector application example

This article example shares the specific code of ...

Docker solves the problem that the terminal cannot input Chinese

Preface: One day, I built a MySQL service in Dock...