我正在使用 Selenium 和 JavaScript 编写测试。我对两者都很陌生,对函数式编程和 Promise 也很陌生。我正在尝试创建一个需要做三件事的函数:
- 点击输入
- 清除输入
- 发送按键进行输入
我当前的功能不起作用:
var clearAndSendKeys = function(driver, elementIdentifier, sendKeys) {
var returnValue;
driver.findElement(elementIdentifier).then(function(inputField){
inputField.click().then(function() {
inputField.clear().then(function() {
returnValue = inputField.sendKeys(sendKeys);
});
});
});
return returnValue;
}
然后将调用该函数,例如:
clearAndSendKeys(driver, webdriver.By.id('date_field'), '14.09.2015').then(function(){
//Do stuff
});
我期望变量 returnValue
包含来自 sendKeys
的 promise 。然而,函数 clearAndSendKeys
在运行 sendKeys 之前返回 undefined variable 。我认为这是因为 returnValue
从未被定义为 promise ,因此程序不知道它需要等待 sendKeys
。
如何让我的函数 clearAndSendKeys
返回来自 sendKeys
的 promise ?我宁愿避免向 clearAndSendKeys
函数添加回调。
编辑:从代码中删除了 .then({return data})
,因为这是一个拼写错误。
最佳答案
您必须从 .then
回调返回每个 Promise:
var clearAndSendKeys = function(driver, elementIdentifier, sendKeys) {
return driver.findElement(elementIdentifier).then(function(inputField){
return inputField.click().then(function() {
return inputField.clear().then(function() {
return inputField.sendKeys(sendKeys);
});
});
});
}
.then
返回的 Promise 将解析为与回调返回的值相同的值。
参见Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference为什么您当前的代码不起作用。 Promise 是异步的。
关于javascript - 如何从 "then"链中的最后一个 promise 返回函数中的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32565577/