javascript - 在 NodeJS 中发布请求后过时的 SQL 数据
问题描述
我有以下功能,一个检索所有表格内容ConnectToDB()
,另一个 INSERT 单个值InsertIntoTable()
。Post 请求的处理方式ConnectToDB()
是在我收到InsertIntoTable()
承诺后调用的。
var express = require('express')
var mysql = require('mysql');
var bodyParser = require('body-parser')
var app = express()
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
function connectToDB()
{
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "*****",
database: "heroes"
});
let myPromise = new Promise(function(myResolve, myReject) {
con.query("SELECT id, name FROM heroes", function (err, result, fields) {
if (err) throw err;
console.log(result);
myResolve(JSON.stringify(result));
});
});
con.release;
return myPromise;
}
function InsertIntoTable(obj)
{
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "******",
database: "heroes"
});
let myPromise = new Promise(function(myResolve, myReject) {
con.query("INSERT INTO heroes (id,name) VALUES ("+obj.id+","+"'"+obj.name+"')", function (err, result, fields){
if (err) myReject(err)
else{
console.log(result);
myResolve(JSON.stringify(result));
}
});
});
con.release;
return myPromise;
}
app.get('/', function (req, res) {
connectToDB().then(result => res.end(result));
})
app.post('/', function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
console.log(req.body);
InsertIntoTable(req.body).then(connectToDB().then(result => res.end(result)));
})
app.listen(8081,function(){
console.log("server is listening...")
})
尽管如此,从通话后收到的记录并没有反映我刚刚创建的新插入的值。
为什么记录已经过时了?不.then()
等待返回的承诺吗?
请务必注意,如果我Get
在操作后发起新呼叫Post
,则返回的记录是最新的。
解决方案
我认为问题在于您在检索记录之前没有等待插入完成。
在这里,您为“then”提供了一个函数,以便在解析 connectToDB 时执行该函数。
app.get('/', function (req, res) {
connectToDB().then(result => res.end(result));
})
您需要为“then()”提供一个函数,否则它将立即执行。
app.post('/', function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
console.log(req.body);
// old line. then is expecting a function but you are just returning data instead
// InsertIntoTable(req.body).then(connectToDB().then(result => res.end(result)));
// waiting for the result of the first promise
InsertIntoTable(req.body)
.then(() => {
// here we are inside a function waiting for the first promise to be resolved
return connectToDB().then(result => res.end(result))
});
});
更好的“结构化”方法:
app.post('/', function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
console.log(req.body);
InsertIntoTable(req.body)
.then(() => connectToDB())
.then(result => res.end(result))
.catch(err => {
// handle you errors here
})
});
推荐阅读
- javascript - Chrome JavaScript 日期构造函数似乎获取 1884 年之前的日期错误
- android-studio-3.0 - 无法加载布局文件
- r - 根据时态数据中的最后一次观察创建条件变量
- vim - 尝试设置 Vundle 时启动 Vim 时出现奇怪的消息
- bash - 如何从日志文件中读取
- angular - Angular 6 路由适用于 ng serve,而不是 Visual Studio
- sql - Hive SQL 将查询应用于许多列
- powershell - 如何使用 PowerShell 导出带有过滤器的 JIRA 报告
- c# - 想检查一个gridview是否包含重复值
- stata - 检查范围是否包含特定值