我正在使用 Angularjs Protractor 进行 e2e 测试,并且我正在尝试对列中的值求和。在循环内,我可以很好地打印出每个值,但我不知道如何将它们全部相加。如果我尝试在 for 循环后返回总计,则它是未定义的。
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;
});
};
最佳答案
另一个(现在是deletec)答案有正确的想法,但 promise 代码庞大且不正确。使用$q.all
(ES6 投诉 promise 实现中的 Promise.all 是我们等待一系列 promise 完成的方式:
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);
});
}
或者,如果您不是 Array#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); });
哪个更干净。
关于javascript - 如何在异步函数中对 Javascript 数组的值求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22918912/