Kosmas Poulianos
Kosmas Poulianos

Reputation: 5

Using node.js & async.js: series executing in the wrong order?

I am using express and async.js for a node application. I have this code in my app.js:

var resultObject = {};

app.get('/average', function(req, res) {
  async.series([
    function(callback) {
  //This does some complex computations and updates the resultObject
      routes.avg(req.query.url, resultObject);
      console.log('1');
      callback();
    }
    ,
    function(callback) { 
      res.send(resultObject);
      console.log('2');
      callback();
    }
  ]);
});

The problem is that the res.send(...) fires before the complex computation in the first function finishes. Therefore, the object sent is empty. Is there some error in my code, or am I not using async.js correctly?

Upvotes: 0

Views: 1080

Answers (2)

Jim Rubenstein
Jim Rubenstein

Reputation: 6930

According to your comments, the problem is that your routes.avg method is asynchronous. This means that the method gets executed but doesn't block the program from continuing, which means that the 2nd closure in your series is being called almost immediately after the 1st one.

The problem isn't that the closures in the async.series call are being called out of order, it's that there's nothing that keeps your callback in closure 1 from being executed before routes.avg is finished.

To fix this, you could pass your callback into your routes.avg call, and edit the routes.avg method so that it calls the callback closure when all the calculation is done. That way, the 2nd closure in your series will not be executed until the callback passed to closure 1 is called by the routes.avg method.

If you don't have access to change the routes.avg method, then you have to find another way to detect when it's done it's work before you call the callback param passed to closure 1 from async.

Upvotes: 1

astone26
astone26

Reputation: 1232

Perhaps try something like this:

async.series([
  function(callback) {
    routes.avg(req.query.url, resultObject);
    console.log('1');
    callback();
  },
  function(callback) { 
    console.log('2');
    callback();
  }
],
function(err, results){
   if(!err)
     res.send(resultObject);
   else
     //do something here for error?
});

Upvotes: 0

Related Questions