承诺永远不会实现

时间:2013-10-21 12:09:01

标签: javascript asynchronous selenium-webdriver

以下代码永远不会命中控制台日志点“post4”或“post3”。它确实回报了承诺,但如果我试图从承诺中脱颖而出,就永远不会遵循这条链。

loginPage.prototype.doLogin = function(isGood){
    var d = webdriver.promise.defer();
    this.driver.findElement(webdriver.By.css('input.loginbutton')).click(function() {
        if(isGood){
            //return new statementPage;
            console.log("post3")
            d.fulfill(new statement.statementPage(this.driver));
        } else {
            console.log("post4")
            d.fulfill(this);
        }
    });
    console.log("post5")
    return d.promise;
}

如果我致电login.doLogin(true).then(function(){console.log("foo")}),它将永远不会记录post3,post4或foo。

我的其他承诺在我的代码中成功运行,所以我不明白为什么这不起作用。

2 个答案:

答案 0 :(得分:2)

webdriverjs的click函数不接受任何参数/回调,因此您的函数从未运行过。 click代码如下(来自API):

webdriver.WebElement.prototype.click = function() {
  return this.schedule_(
      new webdriver.Command(webdriver.CommandName.CLICK_ELEMENT),
      'WebElement.click()');
};

这里有一个fiddle,表明除非使用arguments变量指定,否则不带参数的js函数实际上不会使用该参数。

使用then element.click().then(function(){d.fulfill()});可以实现点击承诺,然后运行您的代码。阅读Webdriverjs Page

的承诺

答案 1 :(得分:1)

而不是使用回调,例如

element.click(function(){d.fulfill(););

您应该使用点击中的承诺,所以:

element.click().then(function(){d.fulfill()});