简体   繁体   English

在量角器中返回函数值时未定义

[英]undefined while returning a function value in protractor

I have a function which returns a value: 我有一个返回值的函数:

checkValue = function(Name){
    var tempIndex=-1;
    var nameIndex=0;
    return selectElement.all(by.tagName('option')).each(function (element) {
        return element.getText().then(function(text){
            tempIndex++;
            if(text.toString().indexOf(Name)!=-1){
                nameIndex=tempIndex;
                return nameIndex;
            }else{
                return nameIndex;
            };
        });
    });

This is called in another function: 这在另一个函数中调用:

checkValue(Name).then(function(value){
    logger.info("value ::"+value);
});

When I call the above function the value is displayed as undefined, and in the logs it gets displayed before the checkValue is called. 当我调用上面的函数时,值显示为undefined,并在日志中显示它,然后调用checkValue

Any suggestions? 有什么建议么?

You are getting undefined since this is what each() returns (returns nothing), implementation : 你是undefined因为这是each()返回(什么都不返回), 实现

ElementArrayFinder.prototype.each = function(fn) {
  return this.map(fn).then(function() {
    return null;
  });
};

Let's approach it differently, using map() : 让我们使用map()来区别map()

return selectElement.all(by.tagName('option')).map(function (option, index) {
    return {
        'text': option.getText(),
        'index': index
    };
}).then(function (options) {
    for (var i = 0; i < options.length; i++) {
        if (options[i].text === Name)
        {
            return options[i].index;
        }
    }
});

I'm still not sure about the motivation side of the question, why do you need an index of an option in the select. 我仍然不确定问题的动机方面,为什么你需要选择中的选项索引。 Anyway, this is something you may consider switching to while dealing with select->option constructions: 无论如何,在处理select->option构造时,您可能会考虑切换到这一点:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM