是否可以异步执行gm_xmlhttprequest?

时间:2018-08-24 00:00:03

标签: javascript asynchronous userscripts tampermonkey gm-xmlhttprequest

我尝试将gm_xmlhttprequest放入while循环中,但是代码同步执行。是否可以使其一次异步执行?

1 个答案:

答案 0 :(得分: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
});