0
votes

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.

1
What is your question? - Quentin
Let me guess, common.commonValidations(db) is also an async function? The thing is, it's async meaning the first function is executed and completed immediately, it doesn't wait for common.commonValidations to get a response, which is why the response is sent (i.e. the second function) is executed virtually immediately. - Adam
@Quentin my question is, how can I fix my code to send response back only after all queries are executed and validations are done? - Naveen
@NaveenChappa — Don't call your callbacks until your queries are complete. - Quentin
@Adam, when the call goes to second function, first function is still executing the queries. First function didn't finish it's job. Is there any solution how I can keep the first function waiting till validation on query results is done? - Naveen

1 Answers

1
votes

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