是否可以异步执行gm_xmlhttprequest?
Is it possible to execute gm_xmlhttprequest asynchronously?
我试过将 gm_xmlhttprequest 放在 while 循环中,但代码是同步执行的。是否可以使其异步执行,一次一个?
最简单的代码更改如下
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
});
我试过将 gm_xmlhttprequest 放在 while 循环中,但代码是同步执行的。是否可以使其异步执行,一次一个?
最简单的代码更改如下
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
});