简体   繁体   English

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

[英]How do I sum the values of a Javascript array in an asynchronous function?

I'm using Angularjs Protractor for e2e tesing, and I'm trying the sum the values in a column.我正在使用 Angularjs Protractor 进行 e2e 测试,我正在尝试对列中的值求和。 Inside the loop I can print out each value fine, but I can't figure out how to add them all.在循环内,我可以很好地打印出每个值,但我不知道如何将它们全部添加。 If I try to return total after the for loop, it's undefined.如果我尝试在 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;
  });
};

The other (now deletec) answer has the right idea but bulky and incorrect promise code.另一个(现在是 deletec)答案有正确的想法,但庞大且不正确的承诺代码。 Using $q.all (Which is Promise.all in ES6 complaint promise implementations is how we wait for an array of promises to complete:使用$q.all (在 ES6 投诉承诺实现中是 Promise.all 是我们等待一系列承诺完成的方式:

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);
    });
}

Alternatively, if you're not an Array#reduce fan you can sum with a for loop.或者,如果您不是Array#reduce粉丝,您可以使用 for 循环求和。

Then, usage is something like:然后,用法类似于:

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

Note, an external promise library like Bluebird would let you do:请注意,像 Bluebird 这样的外部承诺库可以让您执行以下操作:

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

Which is even cleaner.哪个更干净。

Protractor has a buil-in map function.量角器有一个内置的地图功能。

I would recommend you to do something like this:我建议你做这样的事情:

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) {
});

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

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