简体   繁体   中英

how to create callback function in express js with postgresql db?

  1. how to create callback functions properly in this case.

  2. how to wait until query executing the result. This is the code snippet:


app.post('/validate', urlencodedParser, function (req, res) {
    var data = [
        {username:req.body.user, password:req.body.pwd}
    ];
    var disp = function (data,res, callback) {
        return callback(data,res);
    }
    console.log(disp(data,res, LoginCheck));
});

var LoginCheck = function (data,res) {
    var dbresult = [];
    var client = new pg.Client(conString);
    client.connect();
    var query = client.query("SELECT * FROM employee_details");
    query.on("row", function (row, result) {
        result.addRow(row);
    });
    query.on("end", function (result) {      
        dbresult=result.rows;
        console.log(dbresult);
        return dbresult;        
    });
}                                              

You need only one callback function

app.post('/validate', urlencodedParser, function (req, res) {
  var data = [
  {username:req.body.user, password:req.body.pwd}
  ];

 /* var disp = function (data,res, callback) {
    return callback(data,res,callback2);
  }
  console.log(disp(data,res, LoginCheck));
  */

  LoginCheck(data,res, function(result){

    if(result){

      //do whatever you want

      console.log(result)

    }

  })


});

var LoginCheck = function (data,res,callback2) {
  var dbresult = [];
  var client = new pg.Client(conString);
  client.connect();
  var query = client.query("SELECT * FROM employee_details");
  query.on("row", function (row, result) {
    result.addRow(row);
  });
  query.on("end", function (result) {

    dbresult=result.rows;
    console.log(dbresult);
    return callback2(dbresult);

  });
}                                              

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM