Protractor 有自己的 Promise 管理机制,称为控制流,为了简单地理解控制流,你可以认为它是一个队列。
当nodejs逐行执行Protractor脚本时,如果该行中的表达式返回一个promise,控制流会将promise添加到队列中。
所有行执行完成后,您将得到一个 Promise 队列,此时您的测试尚未完成,因为控制流将使您的测试等待队列中的所有 Promise 被执行。现在控制流将从队列中弹出一个 Promise 并执行并等待它完成,然后是下一个 Promise。
所以有了这样的机制,你的脚本就可以按照你写的顺序执行
记录在文件中。实际上控制流所做的事情比我在这里说的更复杂。
在你的情况下,你不需要使用嵌套的 then 链,你的代码就像回调金字塔,不代表承诺的优势(承诺是解决回调金字塔)。您的代码可以很简单,如下所示:
const d = new Date();
//input month
orderCheckOutPage.pageElements.recipientNotificationDateMonth.clear();
orderCheckOutPage.pageElements.recipientNotificationDateMonth.sendKeys(d.getMonth() + 1);
//input day
orderCheckOutPage.pageElements.recipientNotificationDateDay.clear();
orderCheckOutPage.pageElements.recipientNotificationDateDay.sendKeys(d.getDate());
//input year
orderCheckOutPage.pageElements.recipientNotificationDateYear.clear();
orderCheckOutPage.pageElements.recipientNotificationDateYear.sendKeys(d.getFullYear());
对于您的情况,无需使用promise.all(),因为代码的所有交互都不会从页面获取某些值。我将举一个例子来帮助您了解在什么情况下最好使用promise.all():
假设我有一个页面,它显示价格和金额。我需要按价格*金额来计算费用。
使用嵌套然后链:
var fee = ele_price.getText().then(function(price){
return ele_amount.getText().then(function(amount){
return price * amount;
});
});
fee.then(function(fee){
console.log(fee);
});
使用promise.all():
var fee = promise.all([
ele_price.getText(),
ele_amount.getText()
])
.then(function(datas){
var price = datas[0];
var amount = datas[1];
return price * amount;
});
fee.then(function(fee){
console.log(fee);
});
所以用promise.all(),一个then()就够了。这使您的代码比嵌套然后链更具可读性。
希望您现在明白为什么在您的情况下不需要使用promise.all()。