使用JavaScript array.map()回调函数

时间:2017-02-02 19:23:32

标签: javascript protractor angularjs-e2e

我对array.map()示例的困惑是它返回了一个undefined值的数组。 这是Protractor e2e上下文,但非常特定于array.map



this.getColData = function(colIdx){
 var colClass = '.columnUi-' + colIdx;
 var cols = element.all(by.css(colClass));
  
 var that = this;
 return cols.map(function(elem, idx){
   elem.getText().then(function(txt){
     console.log(' COL TEXT: ' + that.convertCellData(txt)); // PRINT CORRECT VALUES
     return that.convertCellData(txt);  
   });            
  }
}




来电者是:

pageObj.getColData(colIdx).then(function(colAry){
     for (var i = 0; i < colAry.length; i++) {
         console.log('--------> [' + i + '] = ' + colAry[i]); // ALL VALUES UNDEFINED
     }
}

getColData()内,console.log()打印正确的值;但是回到来电者的.then()承诺解决方案,他们都是undefined

&#13;
&#13;
---- COLUMN COUNT = 8
 COL TEXT: 0
 COL TEXT: 0
 COL TEXT: 0
 COL TEXT: -2565
 COL TEXT: 8154
 COL TEXT: 5589
 COL TEXT: 5589
 COL TEXT: 5589
--------> [0] = undefined
--------> [1] = undefined
--------> [2] = undefined
--------> [3] = undefined
--------> [4] = undefined
--------> [5] = undefined
--------> [6] = undefined
--------> [7] = undefined
&#13;
&#13;
&#13;

如果我这样写它,它会成功返回新数组:

&#13;
&#13;
        return cols.map(function (elem, idx) {
            elem.getText().then(function (txt) {
                console.log(' COL TEXT: ' + that.convertCellData(txt));                
                colAry.push(that.convertCellData(txt));                
            });
            browser.sleep(200);
        })
        .then(function () {
            return colAry;
        });
&#13;
&#13;
&#13;

0 个答案:

没有答案