等待循环结束执行第二个func

时间:2014-09-07 17:02:02

标签: javascript

我有两个功能:

function parseFriends_new(range) {
var xml = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
        var params = "gwt.requested=" + gwtHash + "&refId=search-d-" + Date.now() + "&d.sq=&d.o=" + range + "&d.d=d.in";
        xml.open("POST", "/dk?cmd=FriendsSearch", true);
        xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xml.setRequestHeader('TKN', TKN);
        xml.onreadystatechange = function() {
            if (4 == xml.readyState && 200 == xml.status) {

            }
        }
        xml.send(params);
}
function postNoteAndTag(friendsList, repostId, trashText) {...}

我需要在postNoteAndTag

之后执行parseFriends_new
for (var i = 0, range = 0; i < 20; i++, range += 10)
{
    parseFriends_new(range);
}
//wait for loop and then execute next code
postNoteAndTag(friendsList, repostId, trashText);

怎么做?

1 个答案:

答案 0 :(得分:0)

由于parseFriends_new是异步的,您可能需要对其进行修改以使其适用于回调:

function parseFriends_new(range, done) {
    var xml = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
    var params = "gwt.requested=" + gwtHash + "&refId=search-d-" + Date.now() + "&d.sq=&d.o=" + range + "&d.d=d.in";
    xml.open("POST", "/dk?cmd=FriendsSearch", true);
    xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xml.setRequestHeader('TKN', TKN);
    xml.onreadystatechange = function() {
        if (4 == xml.readyState && 200 == xml.status) {
        }

        // The AJAX request finished => we can invoke the callback.
        // you could also pass it some result if needed
        done();
    }
    xml.send(params);
}

然后:

// We've got 20 AJAX requests to make at total
var count = 20;
for (var i = 0, range = 0; i < count; i++, range += 10) {
    parseFriends_new(range, function() {
        --count;
        if (count <= 0) {
            // All AJAX requests have finished executing
            // you can now do whatever you intended to do:
            postNoteAndTag(friendsList, repostId, trashText);
        }
    });
}

请记住,这是一个绝对糟糕的做法,在爆炸中用如此多的请求锤击您的Web服务器。这对你的服务器来说很糟糕,对客户来说不好,对TCP / IP来说也不好。

更好的解决方案是使用所有有效负载向服务器发送单个AJAX请求。发送一个大的AJAX请求远比多个小的请求效率高得多。当然,您可能需要调整服务器端脚本以便能够处理请求。