首页 > 解决方案 > 在 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,则返回的记录是最新的。

标签: javascriptnode.jsexpress

解决方案


我认为问题在于您在检索记录之前没有等待插入完成。

在这里,您为“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
         })
    });

推荐阅读