NodeJS中的异步方法

时间:2014-10-10 08:49:16

标签: node.js asynchronous node-async

我想在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

2 个答案:

答案 0 :(得分: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});
});

答案 1 :(得分:0)

在脚本的顶部,您可以:

var total;

这会使用值undefined初始化变量:typeof total === "undefined"; //true

执行此操作时:

total = total + order.price;

你实际上是这样做的:

total = undefined + someNumber

哪个是NaN,因为未定义+ 5不是数字。

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

var total = 0;

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

total += order.price;