量角器函数返回undefined?

时间:2017-02-14 18:03:53

标签: javascript protractor

这更像是一个JavaScript问题,但它正在尝试使用Protractor测试。

//fileA.js
element(by.id('page-element').getText().then(function() {
    var currentPremium = fileB.getSixMonthPremium(); // calls the function in fileB.js

    element(by.id('page-element').getText().then(function() {
        console.log(currentPremium); // prints undefined
        fileB.compareValue(currentPremium, ..., ...,);
    });
});


//fileB.js
this.getSixMonthPremium() = function() {
    element(by.id('full-premium').isDisplayed().then(function(displayed) {
        if (displayed) {
            element(by.id('full-premium').getText().then(function(currentPremium) {
                console.log('Current Premium - ' + currentPremium); // prints string of $XXX.xx
                return currentPremium; //seems to be returning undefined?
            });
        }
    });
});

当从函数调用返回后尝试使用变量currentPremium时,它总是未定义的。我究竟做错了什么?

1 个答案:

答案 0 :(得分:2)

欢迎使用Javascript进行异步调用!

您希望从getSixMonthPremium()来电中退回承诺,然后在该来电回来后继续工作。

this.getSixMonthPremium() = function() {
    return new Promise(function(resolve,reject){
        element(by.id('full-premium').isDisplayed().then(function(displayed) {
            if (displayed) {
                element(by.id('full-premium').getText().then(function(currentPremium) {
                    console.log('Current Premium - ' + currentPremium); // prints string of $XXX.xx
                    resolve(currentPremium); //seems to be returning undefined?
                });
            }
        });
    })
});

然后你会通过做类似下面的事情来处理这个承诺:

fileB.getSixMonthPremium().then(function(premium){
    ...handle premium
});