Node.js和sqlite:在callback中同步
我试图编码以下逻辑:
if account in the DB, then update fields else insert new row with data.
这是一个primefaces操作,所以我把它当做SQL事务(DB是sqlite3):
BEGIN; SELECT rowid FROM Account WHERE email=?; -- Depending on SELECT's result, run INSERT or UPDATE: INSERT INTO Accounts(email, name, phone) VALUES (?, ?, ?); UPDATE Accounts SET name=? phone=? WHERE rowid=?; COMMIT;
我决定在select
的callback中运行insert
或update
。 但是到目前为止,SQL语句不再同步! 在同步块结束和callback执行之间,可以执行任意的SQL语句。
db.synchronized(function() { db.run('BEGIN;'); db.get('SELECT ...;', [...], function(err, row) { // Before this callback is getting executed, there are no sync! // Assume no errors function commit() { // Before this callback is getting executed, there are no sync too! db.run('COMMIT;'); // Use this.lastID } if (row) { db.run('INSERT ...', [...], commit); } else { db.run('UPDATE ...', [...], commit); } }); });
我怎样才能解决这个问题?