I see two problems in your code:
- You call
connection.end() synchronously, but your requests are executed in an asynchronous thread. You should call connection.end() only after the second request completes. - You use the regular
for loop to start asynchronous calls (you can use the outter loop).
To accomplish what you are trying to do, you must consider these asynchronous scripts. You can use promises or a module like async , which provides you with many ways to deal with assyncronous streams, such as async.each() :
connection.query(queryString, function(err, rows, fields) { if (err) throw err; async.each(rows, function (row, callback) { console.log('Product Name: ', row.product_name); var emp_query = 'SELECT * FROM tbl_employer'; connection.query(queryString, function(emp_err, emp_rows, emp_fields) { if (emp_err) callback(emp_err); for (var e in emp_rows) { console.log('Employer Name: ', emp_rows[e].company_name); } callback(); }); }); }, function (err) { connection.end(); } });
Now this ensures that connection.end() will only be called after all of your requests have completed.
source share