我正在做一个 webdriverjs 应用程序,我想检查页面上的 jQuery 何时完成。这是我拥有的方法,但即使其他人应该选择它来停止循环,它也不会中断。循环没有停止。我认为我做错了什么
isjQueryAjaxFinished: function(driver) {
driver.exec('return window.jQuery != undefined && jQuery.active === 0', function(res) {
console.log(res);
return res;
});
},
waitForjQueryAjaxToFinish: function(driver, reason) {
maxTries = 30;
for (i=0; i<maxTries; i++) {
this.isjQueryAjaxFinished(driver, function(res) {
if(res === false) {
driver.sleep(1000).then(function() {
console.log(reason + finished);
});
} else {
return;
}
});
}
}
基本上我想要的是,如果 isjQueryAjaxFinished 返回 false sleep 1 秒,然后重试。如果它返回 true 则继续。就像我上面说的,无论它是真还是假,它都会一直循环,并且只会达到 for 循环的极限。谢谢
最佳答案
Driver.sleep 是异步的。循环在 sleep 调用期间继续。一旦回调在休眠时被调用,循环早就结束了。一种解决方案是使用递归(请注意,您最初调用函数时不需要为“i”提供值)。 (免责声明:下面的代码未经测试......但你明白了。)
var maxTries = 30;
waitForjQueryAjaxToFinish: function(driver, reason, i) {
var iteration = i || 0;
_self = this;
this.isjQueryAjaxFinished(driver, function(res) {
if(res === false) {
driver.sleep(1000).then(function() {
console.log(reason);
if(iteration < maxTries) {
_self.waitForjQueryAjaxToFinish(driver, reason, iteration + 1);
} else {
console.log("Sorry...tried " + maxTries + "times but still no luck.");
return;
}
});
} else {
return;
}
});
}
}
这种方法的一个优点是它是非阻塞的。
关于javascript - Node 功能不中断循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26373716/