[Solved] How to get the number of pending promises? [closed]


Here is a way to do it, where there is no need for an interval timer. It uses a queue of functions to call when the next HTTP response arrives (which makes the number of pending requests to come below 5):

var pending = 0;
var queue = [];

function get(url){
    return new Promise (function(resolve,reject){
        function loop(retries = 3) {
            var xhttp = new XMLHttpRequest();
            xhttp.open("GET",url,true);
            xhttp.onload = function(){
                pending--;
                if (xhttp.status == 200){
                    resolve(JSON.parse(xhttp.response));
                }
                else if (retries > 0) {
                    // retry by automatically relaunching the request:
                    loop(retries-1);
                } else {
                    // give up
                    reject(xhttp.statusText); // correct your spelling!
                }
                if (pending < 5 && queue.length) {
                    // extract and execute the first of the queued actions:
                    queue.shift()();
                }
            };
            xhttp.onerror= function(){
                reject(xhttp.statusText); // correct your spelling
            };
            xhttp.send()
            pending++;
        }
        if (pending >= 5) {
            // Push the call we want to make for later execution in a queue:
            queue.push(loop);
        } else {
            loop(); // try at the most 3 times
        }
    });
}

Here is a snippet with a fake HTTPRequest object in order to simulate both the delay for when there are more than 5 pending requests, and a request that produces an error. All requests take 1 second to get a response, although the last one will produce an error status and will be retried 3 times, and as a consequence its promise only resolves after 3 seconds:

// Overwrite the real XMLHttpRequest with a dummy one, just for this snippet (skip this in your code!):
function XMLHttpRequest() {
    this.open = function(_, url) {
        this.status = url.indexOf('fail') > -1 ? 201 : 200;
        this.response = JSON.stringify({text: 'Response from ' + url});
        this.statusText = this.status == 200 ? 'OK' : 'Error status from ' + url;
    };
    this.send = function () {
        setTimeout(this.onload.bind(this), 1000);
    }.bind(this);
}

var pending = 0;
var queue = [];

function get(url){
    return new Promise (function(resolve,reject){
        function loop(retries = 3) {
            var xhttp = new XMLHttpRequest();
            xhttp.open("GET",url,true);
            xhttp.onload = function(){
                pending--;
                if (xhttp.status == 200){
                    resolve(JSON.parse(xhttp.response));
                }
                else if (retries > 0) {
                    // retry by automatically relaunching the request:
                    loop(retries-1);
                } else {
                    // give up
                    reject(xhttp.statusText); // correct your spelling!
                }
                if (pending < 5 && queue.length) {
                    // extract and execute the first of the queued actions:
                    queue.shift()();
                }
            };
            xhttp.onerror= function(){
                reject(xhttp.statusText); // correct your spelling
            };
            xhttp.send()
            pending++;
        }
        if (pending >= 5) {
            // Push the call we want to make for later execution in a queue:
            queue.push(loop);
        } else {
            loop(); // try at the most 3 times
        }
    });
}

// Example series of calls to illustrate the effect of more than 5 simultanious requests
// and the 3 retries for an error producing request:
console.log('start');
get('example.com?1').then( function(obj) { console.log(obj.text) });
get('example.com?2').then( function(obj) { console.log(obj.text) });
get('example.com?3').then( function(obj) { console.log(obj.text) });
get('example.com?4').then( function(obj) { console.log(obj.text) });
get('example.com?5').then( function(obj) { console.log(obj.text) });
get('example.com?6').then( function(obj) { console.log(obj.text) });
get('example.com?7').then( function(obj) { console.log(obj.text) });
get('example.com?fail').catch( function(msg) { console.log(msg) });
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

solved How to get the number of pending promises? [closed]