javascript - 如何知道有多少异步调用正在等待处理

标签 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");

}

有办法知道吗? 谢谢(:

最佳答案

您可以拦截 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);

关于javascript - 如何知道有多少异步调用正在等待处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23877220/

相关文章:

ios sendAsynchronousRequest定时器

javascript - 如何在html canvas中创建动态绘图文本框

javascript - 两段 javascript 代码,它们可以单独完美地工作,但不能一起工作

javascript - Selenium 网络驱动程序 : Scroll to the top using Javascript

javascript - div动画不重复点击jquery

javascript - 在浏览器中设置 document.domain 使用什么值?

ios - sendAsynchronousRequest 说它在展开可选值时发现 nil

ios - 更好地理解 NSURLConnection 和 NSOperationQueue