【发布时间】:2018-09-13 03:31:57
【问题描述】:
我是编写 node.js 的新手,并且遇到了一些杂乱代码的问题。不知道是不是乱码,可能我只是不习惯node代码吧。
无论如何,代码可以工作,但我对我的错误处理有点不确定,比如某些承诺失败时会发生什么。我尝试在 catch 步骤中进行回滚/释放,但我不确定这是否可以。
还有。这段代码能写得更干净吗?
function insertAnAddress(){
var address = {
country : "A country",
city : "A city",
street : "Random",
number : 6,
postalcode : "A789",
province : "a province"
}
dbpool.getConnection( (err, connection) => {
beginTransaction(connection)
.then( () => {
return insertAddress(address,connection);
})
.then((rows) => {
console.log(rows);
return commitTransaction(connection)
})
.then(()=>{
connection.release();
})
.catch((err) => {
//If rollback fails, the connection will not be released.
//also, is it a good idea to try and do the rollback/release here in the catch?
connection.rollback(() => {
connection.release();
});
throw err;
});
});
});
function beginTransaction(connection){
return new Promise( (resolve, reject) => {
connection.beginTransaction( (err) => {
if (err) {reject(err);}
resolve();
})});
}
function insertAddress(address,connection) {
return new Promise( (resolve, reject) => {
// Do async job
connection.query('INSERT INTO address (country,city,Street,number,postalcode,province) VALUES(?,?,?,?,?,?)', [address.country,'4','5',6,'7','8'] , (err, rows) => {
if (err) {reject(err);}
resolve(rows);
})
})
}
function commitTransaction(connection) {
return new Promise( (resolve, reject) => {
// Do async job
connection.commit(function(err) {
if (err) {reject(err);}
resolve();
})})}
【问题讨论】:
-
稍微清理一下,可以使用
async/awaitdeveloper.mozilla.org/en-US/docs/Web/JavaScript/Reference/…