Tuesday 20 August 2019

Synchronous variable setting in nodejs

Sorry if this is too nooby for the sub. I'm messing around in nodejs and wanted to create variables that are set from db queries and then used later, once the connection is closed.However, as the db call takes nontrivial time, the variable initialization isn't happening until after the final line gets printed.Is there any way to ensure the calls are made synchronously, and the next line waits on the query to finish, without nesting each query?Note that the commented lines work as desired.Snippet:con.connect(function(err) { if (err) throw err; console.log("Connection successful!"); var totalRes; var distinctRes; con.query('select userid,name,address from MYTEST.people;', function (err, result) { if (err) throw err; console.log("Result: " + JSON.stringify(result)); }); con.query('select count(userid) as totalresults from MYTEST.people;', function(error,result) { if(err) throw err; //console.log("There are " + result[0]['totalresults'] + " results, with "); totalRes = result[0]['totalresults']; }); con.query('select count(distinct name, address) as distinctresults from MYTEST.people;', function(error,result) { if(err) throw err; //console.log(result[0]['distinctresults'] + " distinct entries."); distinctRes = result[0]['distinctresults']; }); con.end(); console.log("There are " + totalRes + " results with " + distinctRes + " distinct entries."); }); Output:Connection successful! There are undefined results with undefined unique entries. Result: [*entries*]

Submitted August 21, 2019 at 01:04AM by BallsyPalsy

No comments:

Post a Comment