如何根据Promise值

时间:2018-01-01 20:09:40

标签: javascript typescript protractor

我正在尝试找到一种方法来创建自定义等待某些条件发生。如下所示:

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>
        }
    });
   }
}

但这不起作用。请告诉我如何实现这一目标。

2 个答案:

答案 0 :(得分:1)

我会尝试使用browser.wait函数,它接受第一个参数作为谓词函数,因此你可以编写任何条件,只要你的谓词函数返回true / false或者将被解析为true的Promise就可以工作假的。

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')
}

答案 1 :(得分:0)

除非您使用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
    });
}