Search code examples
javascriptasynchronoususerscriptstampermonkeygm-xmlhttprequest

Is it possible to execute gm_xmlhttprequest asynchronously?


I've tried putting gm_xmlhttprequest inside a while loop but the code executes synchronously. Is it possible to make it execute asynchronously, one at a time?


Solution

  • simplest change to your code would be as follows

    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);
    

    i.e. in the onload, run the next iteration ... this will result in the requests being made sequentially

    If you need to run this code, then when all requests are finished continue on to do something else

    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
    });