如何对异步函数中Javascript数组的值求和?

如何对异步函数中Javascript数组的值求和?,javascript,angularjs,promise,protractor,angular-promise,Javascript,Angularjs,Promise,Protractor,Angular Promise,我正在使用Angularjs量角器进行e2e测试,我正在尝试对列中的值求和。在循环中,我可以很好地打印出每个值,但我不知道如何将它们全部相加。如果我尝试在for循环之后返回total,它是未定义的 function getTotal() { ptor.findElements(protractor.By.className('col33')).then(function(promColCells) { var total; for (var i = 2; i < pro

我正在使用Angularjs量角器进行e2e测试,我正在尝试对列中的值求和。在循环中,我可以很好地打印出每个值,但我不知道如何将它们全部相加。如果我尝试在for循环之后返回total,它是未定义的

function getTotal() {
  ptor.findElements(protractor.By.className('col33')).then(function(promColCells) {
    var total;
    for (var i = 2; i < promColCells.length; i += 2) {
      promColCells[i].getText().then(function(promCellString) {
        total += parseFloat(promCellString);
      });
    }
    return total;
  });
};
函数getTotal(){ ptor.findElements(progrator.By.className('col33'))。然后(function(promColCells){ 总风险价值; 对于(变量i=2;i另一个(现在是deletec)答案的想法是正确的,但其承诺代码庞大且不正确。使用
$q.all
(这是Promise.all,在ES6投诉承诺实施中,我们是如何等待一系列承诺完成的:

function getTotal() {
    // we return the continuation here
    return ptor.findElements(protractor.By.className('col33')).then(function(cells) {
        // wait for all cells  
        return $q.all(cells.map(function(cell){ return cell.getText()}));
    }).then(function(cellTexts){
        return cellTexts.reduce(function(x,y){ return x + Number(y);},0);
    });
}
或者,如果你不是
数组#reduce
粉丝,你可以用for循环求和

然后,用法类似于:

getTotal().then(function(total){
    alert(total); // total value available here
});

注意,像Bluebird这样的外部promise库可以让您做到:

return Promise.cast(ptor.findElements(protractor.By.className('col33')))
    .map(function(cell){ return cell.getText(); })
    .reduce(function(x,y){ return x+Number(y); });

它甚至更干净。

量角器具有内置地图功能

我建议您这样做:

function getTotal() {
  // The same as element.all(by.css('.col33')). It will return
  // a promise that resolves to an array os strings.
  return $$('.col33').map(function(cell){
    return cell.getText();
  }).
  then(function(values){
     // Values is an Array.<string> parse the ints and return the value.
     var result = 0;
     values.forEach(function(val){
       result += parseInt(val, 10);
     });
     return result;
  });
};

getTotal.then(function(total) {
});
函数getTotal(){ //与element.all(by.css('.col33')相同。它将返回 //解析为数组os字符串的承诺。 返回$$('.col33').map(函数(单元格){ 返回cell.getText(); }). 然后(函数(值){ //值是一个数组。分析整数并返回值。 var结果=0; 值。forEach(函数(val){ 结果+=parseInt(val,10); }); 返回结果; }); }; getTotal.then(函数总数){ });
这些操作是异步的吗?如果是,你就不能同步返回一系列异步操作的总数?如果这些操作不是异步的,那么我就想弄明白为什么你还要尝试使用承诺,因为必须有一种更简单的方法。这些操作是异步的,这是我最困惑的。然后,你就可以了永远不要从
getTotal()
同步返回
total
,因为当
getTotal()
返回时它还没有完成。您需要让
getTotal()
返回一个承诺,并在计算
total
时解析该承诺,或者让
getTotal()返回该承诺
取一个回调函数,调用该回调函数,并在完成计算后传递其总数。您必须重新构造它。非常感谢,我现在理解了。是否有额外的/缺少的大括号或其他东西?我得到了一个
意外标记}
错误。老实说,我不知道,我在堆栈溢出中键入了它,没有测试它-jusI don’我不想通过一个点,让我在一秒钟内找到它。第5行可能缺少一个
?谢谢你,Andres,这很有帮助