我是编写node.js的新手,并且遇到了一些乱码的问题。我不一定知道它是否凌乱,也许我只是不习惯节点代码。
无论如何,代码可以运行,但我对我的错误处理有点不确定,比如当某些promise失败时会发生什么。我尝试在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();
})})}
答案 0 :(得分:0)
一些建议:
1)使用util.promisify将回调样式转换为Promise样式,而不是Promise构造函数
2)当箭头函数由单个return语句组成时,删除花括号并返回关键字。
3)使用finally
释放连接,无论是否有错误。
结果:
const util = require('util');
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( () => insertAddress(address,connection) )
.then((rows) => {
console.log(rows);
return commitTransaction(connection);
})
.catch(util.promisify(connection.rollback.bind(connection)))
.finally( () => connection.release() );
});
});
function beginTransaction(connection){
return util.promisify(connection.beginTransaction.bind(connection))();
}
function insertAddress(address,connection) {
return util.promisify(connection.query.bind(connection))(
'INSERT INTO address (country,city,Street,number,postalcode,province) VALUES(?,?,?,?,?,?)',
[address.country,'4','5',6,'7','8']
);
}
function commitTransaction(connection) {
return util.promisify(connection.commit.bind(connection))();
}
您还可以使用像mysql-promise这样的util.promisify
库或更好的IMO来使用像{{3}这样的Promise库来删除所有mysql
调用它有一个bluebird函数。