如何从量角器的外部函数返回整数作为承诺?

时间:2019-01-16 22:26:05

标签: protractor

我编写了一个外部函数,该函数接受一个参数并计算某些事件的出现,这些事件以整数形式存储在变量totalNumToAck中。然后,我尝试返回该计算出的整数作为已兑现的承诺,并在以后使用它。我调用该函数并将参数成功传递给它。它做了它需要做的事情,但是我很难返回结果。 在我尝试使用的代码中,它始终为0。能否请您指出我做错了什么?

编辑:实际上看起来第二种方法可行,而我的实际问题是由于异步执行而导致的外部函数本身。代码到达这一行:deferred.fulfill(totalNumToAck); 在for循环之前完成,因此总是返回0。因此,新问题是如何使我的返回等待“ for循环”完成?

我的简化代码如下:

//The function I want to call, which is in a different file:


MyExternalFunction(numOfLines)  {

    var totalNumToAck =0;
    var deferred = protractor.promise.defer();


    for (var i = 0; i < numOfLines; ++i) {  
            //code to analyze the page      
            if (somecondition) {
                totalNumToAck++;
                }

    }
    console.log('found' + totalNumToAck + 'elements');
    deferred.fulfill(totalNumToAck);
    return deferred.promise;

};

//The code where I try to use the function - Edit: this actually works! but the problem is in ext function

myextstuff.MyExternalFunction(5).then(function (totalNumToAck ) {
    console.log ("number returned from ext function: " + totalNumToAck );
    //other code that needs to use integer value that external function returns
});

//Also tried - Edit: this actually works too! but the problem is in ext function
response = myextstuff.MyExternalFunction(5);
response.then(function(cellValue){   
    console.log ("number returned from ext function: " + cellValue);
    totalNumToAck =  cellValue;
    //other code that needs to use integer value that external function returns
        });

2 个答案:

答案 0 :(得分:0)

您可以尝试以下尝试

# Java 1.8
RUN apt-get install -y software-properties-common && \
    add-apt-repository ppa:webupd8team/java -y && \
    apt-get update && \
    echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections && \
    apt-get install -y oracle-java8-installer && \
    apt-get clean

答案 1 :(得分:0)

我能够使用for循环解决我的问题。我的外部函数现在看起来像:

MyExternalFunction(numOfLines)  {
    var totalNumToAck =0;
    var deferred = protractor.promise.defer();

    browser.wait(function () {
       return SomeElementThatIKnowIsPresent.isPresent();
    }, 50000).then(function () {
    for (var i = 0; i < numOfLines; ++i) {  
            //code to analyze the page      
            if (somecondition) {
                totalNumToAck++;
                }

    }
    }).then(function () {
        console.log('found' + totalNumToAck + 'elements');
        deferred.fulfill(totalNumToAck);
    });

    return deferred.promise;
};

这确保for循环将结束,然后才推迟。fulfill(totalNumToAck);将会发生。谢谢您的帮助。