i ran issue whilst attempting create logic add rows new table made on mysql database. when adding row need query database 4 times check other rows , add correct value new row. using node.js , mysql module accomplish this. while coding ran snag, code not wait 4 queries finish before inserting new row, gives values being found value of 0 every time. after research realize callback function in order, looking this:
var n = 0; connection.query("select...", function(err, rows){ if(err) throw err; else{ if(rows.length === 1) ++n; } callback(); }); function callback(){ connection.query("insert...", function(err){ if(err) throw err; }); } note: select queries can return 1 item if condition should not effect issue.
a callback function 1 query wait on clear me, become bit lost multiple queries wait on. idea had create variable increments before callback called, , passed in callback function's arguments. inside callback query encapsulated if statement condition of being variable equaling number of queries need called, 4 purposes here. see working wasn't sure if sort of situation has built in solution or if there other, better, solutions developed.
you need async (https://github.com/caolan/async). can complex logic module.
var data = {} //you can in many ways 1 way defining global object can add things object , every function can see firstqueryfunction(callback){ //do stuff mysql data.stuff = rows[0].stuff; //you can store stuff inside data object callback(null); } secondqueryfunction(callback){ //do stuff mysql callback(null); } thirdqueryfunction(callback){ //do stuff mysql callback(null); } fourthqueryfunction(callback){ //do stuff mysql callback(null); } //this functions executed @ same time async.parallel([ firstqueryfunction, secondqueryfunction, thirdqueryfunction, fourthqueryfunction ], function (err, result) { //this code executed after previous queries done (the order doesn't matter). //for example can query depends of result of previous queries. });
Comments
Post a Comment