質問

I'm wondering if it is possible to make a series of calculations and get the returned value using async.each method. A very simple example of it would be calculating the sum of all elements in an array.

function Calculator() {

}

Calculator.prototype.sum = function(elements, callback) {
  var total = 0;
  async.each(elements, function(element, callback) {
    total += element;
    callback();
  }, function(err) {
    if (err) throw err;
    //How can I get total as a returned value of sum?
  });
}

Thanks

役に立ちましたか?

解決

Yes it should be possible: You could use async.reduce. (Although this would required some changes to your code, the current value must be passed through with the callback.

Example from the docs:

async.reduce([1,2,3], 0, function(memo, item, callback){
    // pointless async:
    process.nextTick(function(){
        callback(null, memo + item)
    });
}, function(err, result){
    // result is now equal to the last value of memo, which is 6
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top