[英]Do I need the promise in my MySQL statement?
Below is a MySQL statement in my Node.js app. 以下是我的Node.js应用程序中的MySQL语句。 I used a promise in MySQL function to get API endpoint to work.
我在MySQL函数中使用了promise来使API端点正常工作。 Is this a typical pattern for Node.js and MySQL?
这是Node.js和MySQL的典型模式吗?
const express = require('express');
const app = express();
app.use(express.static('client'));
const config = require('./config')
var mysql = require('mysql');
var con = mysql.createConnection({
host: config.HOST,
user: config.USER,
password: config.PASSWORD,
database: config.DATABASE
});
function GetConsumers(req, res) {
return new Promise(function (resolve, reject) {
con.connect(function (err) {
if (err) throw err;
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) throw err;
//console.log(result);
resolve(result);
});
});
}).then(rows => res.send(rows));
}
app.get('/consumers', GetConsumers);
module.exports = app;
As George commented, you don't really need to return a promise here. 正如George所评论的那样,您实际上不需要在这里退还诺言。
function GetConsumers(req, res) {
con.connect(function (err) {
if (err) {
res.send(err)
};
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) {
res.send(err)
};
//console.log(result);
res.send(result)
});
});
} }
If you really want to use promises, it is always a good practice to catch the exceptions. 如果您确实要使用Promise,则捕获异常始终是一个好习惯。
function GetConsumers(req, res) {
return new Promise(function (resolve, reject) {
con.connect(function (err) {
if (err){
reject(err);
}
con.query("SELECT * FROM " + config.DATABASE + ".Contracts",
function (err, result, fields) {
if (err){
reject(err);
}
//console.log(result);
resolve(result);
});
});
})
} }
Call GetConsumers function where ever you want it. 在任何需要的地方调用GetConsumers函数。
GetConsumers(req,res).then(rows => res.send(rows))
}).catch(err =>{
console.log("Handle your error here");
res.send("error")
})
Mysql npm has good documentation of how to use the module. Mysql npm拥有有关如何使用该模块的良好文档。 You can refer it more here
你可以在这里参考更多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.