节点函数未中断循环

Node functions not breaking loop

本文关键字:循环 中断 函数 节点      更新时间:2023-09-26

我正在做一个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在1秒内返回假睡眠,然后重试。如果返回true,则继续。就像我上面说的,无论是真是假,它都会保持循环,并且刚好达到for循环的极限。感谢

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

这种方法的一个优点是它是非阻塞的。