[英]How to wrap loop and promise and break loop based on Promise value
我試圖找到一種方法來創建自定義等待某些條件發生。 如下所示:
static waitForActivityToHappen(activityName: string, timeout: number) {
const startTime = PageHelper.getCurrentTime(); // Get current time in milisecond
while ((PageHelper.getCurrentTime() - startTime) < timeout) {
browser.sleep(PageHelper.timeout.xxs); // Poll every 1 sec
<Do some action here>
element.all(By.xpath(xpath)).count().then(function (count) {
if (count > 0) {
<break the loop here>
}
});
}
}
但這是行不通的。 請讓我知道如何實現。
我會嘗試使用browser.wait函數,它接受第一個參數作為謂詞函數,因此您可以編寫任何條件,並且只要您的謂詞函數返回true / false或Promise(將被解析為true / false),它就可以工作。
static waitForActivityToHappen(activityName:string, timeout: number) {
let waitForActivityToHappenPredicate = function () {
return element.all(By.xpath(xpath)).count().then(function () {
if (count > 0) {
return true
} else {
return false
}
}, function (err) {return false})
}
browser.wait(waitForActivityToHappenPredicate, timeout, 'Some timeout message here')
}
除非使用ES2017 + async
函數和await
否則不能將循環結構與異步代碼一起使用。 相反,您必須安排當前迭代的下一個迭代。 這是一個這樣做的例子:
static waitForActivityToHappen(activityName: string, timeout: number) {
const startTime = PageHelper.getCurrentTime(); // Get current time in milisecond
// Start the process
tick();
function tick() {
browser.sleep(PageHelper.timeout.xxs) // Poll every 1 sec
.then(() => /*...do some action here perhaps...*/)
.then(() => element.all(By.xpath(xpath)).count())
.then(count => {
if (count > 0) {
// Done
} else if ((PageHelper.getCurrentTime() - startTime) < timeout) {
// Try again
tick();
} else {
// Timed out
}
})
.catch(err => {
// do something with the error
});
}
}
如果您可以使用ES2017 +功能,則可以使用while
循環編寫該功能(將像上面那樣處理):
static waitForActivityToHappen(activityName: string, timeout: number) {
const startTime = PageHelper.getCurrentTime(); // Get current time in milisecond
// Use an async function so we can use logical flow
(async() => {
// Note `await` in the below
while ((PageHelper.getCurrentTime() - startTime) < timeout) {
await browser.sleep(PageHelper.timeout.xxs); // Poll every 1 sec
/*...do some action here perhaps; if it's async, await it...*/
const count = await element.all(By.xpath(xpath)).count();
if (count > 0) {
// Done
break;
}
}
})().catch(err => {
// do something with the error
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.