之前在一个页面写了好多代码,有点冗杂,把具体的逻辑代码封装一下;
有些方法需要Promise
示例:
function serverYDYN() {
//修改
this.updateContent = function (id, newContent) {
var promise = new Promise(function (resolve, reject) {
pool.getConnection((err, connection) => {
if (err) {
console.log("连接失败");
} else {
let sql = "UPDATE ydyn1 SET content='" + newContent + "'WHERE id='" + id + "'";
connection.query(sql, function (err, result) {
if (err) {
console.log('[修改content错误] - ', err.message);
return reject(err);
}
console.log('修改content result:\n', result);
return resolve(result);
});
connection.release();
}
});
});
return promise;
};
}
module.exports = serverYDYN;
使用:
const serverYDYN = require('./sqlServerYDYN');
app.put('/updateContent', function (request, res) {
let newContent = request.body.content;
let id = request._parsedUrl.query;
sqlServer.updateContent(id,newContent).then(
result => {
console.log('修改成功 res',result);
res.send('sucess');
}
).catch(
err => {
console.log('修改错误',err)
}
);
});