[英]How to break out of a JavaScript loop
這是我的 function,我想在滿足條件時打破廁所,但出現錯誤:
SyntaxError: 非法的 break 語句
我正在使用 protractor 和 javascript。
async CompareTableData(byElement, param) {
try {
await this.WaitToBeClickable(element(By.cssContainingText(byElement.value, param)));
await element.all(byElement).then(async function(item) {
for (var i = 0; i < item.length; i++) {
item[i].getText().then(async function(text) {
var trimTxt = text.trim();
if (await trimTxt == param && byElement.using == "css selector") {
console.log(`Param FOUND! ${param}\n`);
await expect(element(By.cssContainingText(byElement.value, param)).isPresent()).toBe(true);
break;
} else {
return;
}
});
}
});
} catch (err) {
console.log("Table comparison FAILED, element not present!");
return console.log(err);
}
};
正如其他人指出的那樣,你的 break 不在你的循環中,而是在你的 .then 中的匿名.then
中。 除此之外,主要問題是你沒有很好地履行你的承諾。 引入Async/await
是為了通過不要求您使用.then
語句來簡化處理承諾,因此您絕對不應該以這種方式一起使用它們。
還expect
語句是同步的,因此不需要等待,但是在使用 Protractor 時,期望中的操作(幾乎總是)是異步的,因此該語句應讀取expect(await element(By.cssContainingText(byElement.value, param)).isPresent()).toBe(true);
您可以像這樣重寫代碼:
async function CompareTableData(byElement, param) {
try {
await this.WaitToBeClickable(element(By.cssContainingText(byElement.value, param)));
const item = await element.all(byElement)
for (var i = 0; i < item.length; i++) {
const text = await item[i].getText();
var trimTxt = text.trim();
if (trimTxt == param && byElement.using == "css selector") {
console.log(`Param FOUND! ${param}\n`);
expect(await element(By.cssContainingText(byElement.value, param)).isPresent()).toBe(true);
break;
} else {
return;
}
}
} catch (err) {
console.log("Table comparison FAILED, element not present!");
return console.log(err);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.