Code implementation

// Set concurrency limits for network requests. The NetManager(concurrency) constructor passes in a number, which is the maximum number of concurrent requests, and provides the request(URL, data) => Promise
      
        method
      
// Const obj = new NetManager(5)
/ / obj. Request ("/XXX/SSS ",} {a: 1)

// index.js
class NetManager {
    constructor(number) {
        if(! (typeof number === 'number'&&!Number.isNaN(number))) {
            console.error(
                `NetManager params typeof number === 'The ${typeof number}', value: ${number}`
            );
        }

        this.number = number;
        this.queues = [];
        this.caches = [];
    }

    trigger = () = > {
        const hits = this.queues.filter((i) = > i.isFetch === false);
        hits.forEach((item) = > {
            item.isFetch = true;

            item.task()
                .then(item.resolve)
                .catch(item.reject)
                .finally(() = > {
                    const deleteIndex = this.queues.findIndex(
                        (del) = > del.key === item.key
                    );

                    if(deleteIndex ! = = -1) {
                        this.queues.splice(deleteIndex, 1);
                    }

                    if (this.caches.length > 0) {
                        this.queues.push(this.caches.shift());
                        this.trigger(); }}); }); }; request =(. reset) = > {
        return new Promise((resolve, reject) = > {
            // Bind a function and pass the parameter
            const task = window.fetch.bind(null. reset);// Generates a key value that is used to delete the queue task
            const key = Math.random();

            const newItem = {key, isFetch: false, task, resolve, reject};
            if (this.queues.length >= this.number || this.caches.length > 0) {
                this.caches.push(newItem);
            } else {
                this.queues.push(newItem);
                this.trigger(); }}); }; }const JSON_PLACEHOLDER = 'https://jsonplaceholder.typicode.com/todos/';

const obj = new NetManager(2);

for (let i = 1; i <= 10; i++) {
    obj.request(`${JSON_PLACEHOLDER}${i}`, {credentials: 'include'})
        .then((res) = > res.json())
        .then((result) = > {
            console.log('result', result);
        });
}

Copy the code

index.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <script src="./index.js"></script>
</body>
</html>
Copy the code

The execution result

Open index.html in your browser