tonymx227
tonymx227

Reputation: 5451

Async method in NodeJS

I'd like to make an addition using Async() in NodeJS but it doesn't work...

My code :

    var id = request.params.id;
    var self = this;
    var total;
    var asyncTasks = [];

asyncTasks.push(function(callback){
  self.orderDao.getAllOfUser(id).success(function (orders) {
    orders.forEach( function(order){
      total = total + order.price; // here I'd like to make the addition
      console.log(total);
    });
  });
  callback();
});

    async.parallel(asyncTasks, function(){
      self.orderDao.getAllOfUser(id).success(function (orders) {
        response.render('order/index', {orders: orders, total: total});
      });
    });

Result of total : NaN

Upvotes: 0

Views: 481

Answers (2)

Michael
Michael

Reputation: 1322

this is how its done with parallel, in you attempt the first callback was been called right after the start of getAllOfUser(id) without waiting for the response. it was just luck that your finish callback run long enough for the total aggregation to finish:

var id = request.params.id;
var self = this;

async.parallel({
  total: function(callback){
    self.orderDao.getAllOfUser(id).success(function (orders) {
      var total=0;
      orders.forEach( function(order){
        total = total + order.price; // here I'd like to make the addition
        console.log(total);
      });
      callback(null, total);
    });
  },
  orders: function (callback) {
    self.orderDao.getAllOfUser(id).success(function (orders) {
      callback(null, orders);
    });
  }
}, function(err, res){
  response.render('order/index', {orders: res.orders, total: res.total});
});

But there is a better solution where you wouldn't need to do getAllOfUser twice. like:

var id = request.params.id;
var self = this;
var total=0;
self.orderDao.getAllOfUser(id).success(function (orders) {
  orders.forEach( function(order){
    total = total + order.price; // here I'd like to make the addition
    console.log(total);
  });
  response.render('order/index', {orders: orders, total: total});
});

Upvotes: 1

RickN
RickN

Reputation: 13500

At the top of your script, you do:

var total;

This initialises the variable with the value undefined: typeof total === "undefined"; //true

When you do this:

total = total + order.price;

You're actually doing this:

total = undefined + someNumber

Which is NaN, because undefined+5 is not a number.

To fix this, change the declaration at the top of your script to:

var total = 0;

Also you can (but don't have to) shorten the addition in the loop to:

total += order.price;

Upvotes: 0

Related Questions