Naveen
Naveen

Reputation: 947

Node JS - Async - Response is sent while queries are being executed

I am using the below piece of code to execute some set of queries and send the response of doing some validations on query results. For this scenario, I am using async module in Node JS.

async.series([
           function(callback){
               common.commonValidations(db);
               callback();
           },
           function(callback){
                console.log('second function');
                res.end(JSON.stringify(gErrors));
                callback();
           }

        ], function(err){
            console.log('sending res to client');
            console.log(err);
        });

common.commonValidations(db) function is used to execute few db2 queries.

Here my issue is, though I am using async module, the response is sent to the client while the query execution is going on. As per my understanding of async module, the second function in the array is executed once the first function is done with it's job.

Can someone help me on this? Thanks in advance.

Upvotes: 0

Views: 107

Answers (1)

Jaffer
Jaffer

Reputation: 2968

Looks like common.commonValidations(db) is an asynchronous function, but you are not waiting for it to be done. you are calling callback() function before the answer for commonValidations comes back.

one possible change might be like

common.commonValidations(db,function(err,data) {
  //check error
  //process data
  //and then
  callback()
})

Upvotes: 1

Related Questions