我使用以下函数处理多个查询事务:
function waterfall (tasks, callback) {
pg.connect(conString, function (err, client, done) {
if (err) {
return callback(err);
}
//client.query(begin_transaction, function (err) {
client.query('BEGIN', function (err) {
if (err) {
done();
return callback(err);
}
var wrapIterator = function (iterator) {
return function (err) {
if (err) {
//client.query(rollback_transaction, function () {
client.query('ROLLBACK', function () {
done();
callback(err);
});
}
else {
var args = Array.prototype.slice.call(arguments, 1);
var next = iterator.next();
if (next) {
args.unshift(client);
args.push(wrapIterator(next));
}
else {
args.unshift(client);
args.push(function (err, results) {
var args = Array.prototype.slice.call(arguments, 0);
if (err) {
//client.query(rollback_transaction, function () {
client.query('ROLLBACK', function () {
done();
callback(err);
});
}
else {
//client.query(commit_transaction, function () {
client.query('COMMIT', function () {
done();
callback.apply(null, args);
})
}
})
}
async.setImmediate(function () {
iterator.apply(null, args);
});
}
};
};
wrapIterator(async.iterator(tasks))();
});
});
}
(简称http://baudehlo.com/2014/04/28/node-js-multiple-query-transactions /)
以下功能有什么问题:
db.waterfall([
function(client,cb){
client.query("INSERT INTO mydb.plotsold" +
"(plot_id, agent_id, plot_price, plot_date) VALUES " +
"($1,$2,$3,$4) RETURNING id", soldInfo.PlotId, soldInfo.agentId,
soldInfo.soldPrice, soldInfo.newDate,cb);
},
function(client,results,cb){
client.query("update mydb.listing " +
"set status =2 where id = $1 RETURNING id",soldInfo.listingId,cb);
}
],cb);