1

我尝试将 gm_xmlhttprequest 放在 while 循环中,但代码是同步执行的。是否可以让它异步执行,一次一个?

4

1 回答 1

1

对代码的最简单更改如下

function doXHR(counter) {
    if (counter < count) {
        var GoToURL = link;
        GM_xmlhttpRequest({
            method: "GET",
            url: GoToURL,
            onload: function(response) {
                if (response.finalUrl.match(/true$/)) { 
                    longList = longList + link; 
                }
                doHXR(counter+1);
            }
        });
    }
}
doXHR(0);

即在onload中,运行下一次迭代......这将导致请求按顺序发出

如果您需要运行此代码,则在所有请求完成后继续执行其他操作

function doAllXHR(count, callback) {

    function doXHR(counter) {
        if (counter < count) {
            var GoToURL = link;
            GM_xmlhttpRequest({
                method: "GET",
                url: GoToURL,
                onload: function(response) {
                    if (response.finalUrl.match(/true$/)) { 
                        longList = longList + link; 
                    }
                    doHXR(counter+1);
                }
            });
        } else {
            callback('done');
        }
    }
    doXHR(0);
}

doAllXHR(20, function(result) {
    console.log(result);
    // and continue with whatever it is you do
});
于 2018-08-24T00:42:38.390 回答