0

我想在 NodeJS 中使用 Async() 进行添加,但它不起作用......

我的代码:

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

结果total:NaN

4

2 回答 2

1

这就是并行完成的方式,在您尝试在 getAllOfUser(id) 开始后立即调用第一个回调而不等待响应。幸运的是,您的完成回调运行了足够长的时间以使总聚合完成:

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

但是有一个更好的解决方案,您不需要执行两次 getAllOfUser 。像:

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});
});
于 2014-10-10T09:13:14.940 回答
0

在脚本的顶部,您执行以下操作:

var total;

这将使用值初始化变量undefinedtypeof total === "undefined"; //true

当你这样做时:

total = total + order.price;

你实际上是这样做的:

total = undefined + someNumber

也就是说NaN,因为 undefined+5 不是数字。

要解决此问题,请将脚本顶部的声明更改为:

var total = 0;

您也可以(但不必)将循环中的加法缩短为:

total += order.price;
于 2014-10-10T09:09:37.863 回答