如何知道有多少异步调用待处理

时间:2014-05-26 20:22:08

标签: javascript sendasynchronousrequest

我正在使用以下代码进行多重异步。电话,我需要知道有多少电话正在等待验证。

function llenarComboMetodos(cell) {
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Las llamandas asincronas no son soportadas por este navegador.");
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status == 200 && xhr.status < 300) {
                var combo = '<select name="metodos[]">';
                var opciones=xhr.responseText;
                combo+= opciones+"</select>";
                cell.innerHTML = combo;
            }
        }
    }

    xhr.open('POST', 'includes/get_metodos.php');
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("completar=1");

}

有没有办法知道这个? 谢谢(:

1 个答案:

答案 0 :(得分:1)

您可以拦截XMLHttpRequest.send并计算有效来电:

var activeXhr = (function(){
    var count = 0;
    XMLHttpRequest.prototype.nativeSend = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.send = function(body) {

        this.onreadystatechange  = function(){
            switch(this.readyState){
                case 2: count++; break
                case 4: count--; break
            }
        };
        this.nativeSend(body);
    };

    return count;
})();

console.log(activeXhr);