Asynchronous Database Problems with Node.js -
i trying query database, running on node server without express using sqlite3, check if element in database. upon finding if element exists, go on access different table information.
var username; checksessionid(userssessionid, function(temp) { username = temp[0].username; }); var db = new sql.database("pete's fcrs.db"); var ps = db.prepare("select * users username = ?", errorfunc); ps.all(username, function(err, rows) { if (err) throw err; console.log(rows); }); ps.finalize(); db.close(); function checksessionid(sessionid, callback) { var db = new sql.database("pete's fcrs.db"); var ps = db.prepare("select * sessionids sessionid = ?", errorfunc); ps.all(sessionid, function(err, rows) { if (err) throw err; callback(rows); }); ps.finalize(); db.close(); } ("test: " + sessiondetails);
1) run checksessionid check if sessionid in database, in sessionids table. 2) next, calls callback function, store username associated session id.
however, due fact callbacks asynchronous, accessing database prior "username" being updated.
to attempt solve this, not possible move database queries inside callback function, causes error, database locked.
many help.
edit
managed solve it, declaring db global variable , closing after process have completed.
generally when writing asynchronous code need move code inside callback, otherwise fires immediately:
var db = new sql.database("pete's fcrs.db"); var ps = db.prepare("select * users username = ?", errorfunc); ps.all(username, function(err, rows) { if (err) throw err; console.log(rows); ps.finalize(); db.close(); });
remember code executing out of order, not 1 line next.
i've found using promise library bluebird helps simplify code considerably , makes easier follow. promises can take moment absorb, they're new concept, once know how work things chain lot better.
a promise-version of code like:
ps.all(username) .then(function(rows) { console.log(rows); }) .then(function() { return ps.finalize(); }) .then(function() { return db.close(); })
error catching done automatically , it's possible add special handlers if desired.
Comments
Post a Comment