同一个函数中的两个客户端查询

时间:2022-06-21 01:06:33

I have a question about if it is right to do two client.queries one right after the other. I am trying to build a REST API. Example:

我有一个问题,是否一个接一个地做两个client.queries是正确的。我正在尝试构建REST API。例:

client.query("select waiters_id from waiters", function(err, result){
                     if(err){
                         res.json({success: false, msg: "error"});
                     }
                     if(result.rows.length === 0){
                         done();
                         res.json({success: false, msg: "error"});
                     } else{
                         if(results.rows[0].waiter_id === req.body.waitid){
                                 done();
                                 res.json({success: true, msg: "proceed"});
                             }
                         client.query("insert into waiters",function(err, result){
                              // MORE CODE
                         });

I am trying to check if there is a waiter in the waiters table, then insert some specific information into that waiter in that waiters table if there is a waiter. If there is a better way to do this please let me know. I don't want to lose performance. Thanks

我试图检查服务员表中是否有服务员,然后如果有服务员那么将一些特定信息插入该服务员表中的服务员。如果有更好的方法,请告诉我。我不想失去表现。谢谢

1 个解决方案

#1


1  

This question really has more to do with SQL then nodejs/express. SQL provides you with the ability to use if statements to make logical assertions about your results:

这个问题确实与SQL有关,然后是nodejs / express。 SQL使您能够使用if语句对结果进行逻辑断言:

client.query(
  "IF EXISTS (SELECT * FROM waiters WHERE waiters_id='SomeValue')
      UPDATE waiters SET (...) WHERE waiters_id='SomeValue'
   ELSE
      INSERT INTO waiters VALUES (...)
   SELECT * FROM waiters",
  function (err, result) {
     // do something with results here     
  }
);

Which is essentially the same control logic you are trying to build with nodejs. Using the above would eliminate the need for another query.

这与您尝试使用nodejs构建的控制逻辑基本相同。使用上述内容将消除对另一个查询的需要。

#1


1  

This question really has more to do with SQL then nodejs/express. SQL provides you with the ability to use if statements to make logical assertions about your results:

这个问题确实与SQL有关,然后是nodejs / express。 SQL使您能够使用if语句对结果进行逻辑断言:

client.query(
  "IF EXISTS (SELECT * FROM waiters WHERE waiters_id='SomeValue')
      UPDATE waiters SET (...) WHERE waiters_id='SomeValue'
   ELSE
      INSERT INTO waiters VALUES (...)
   SELECT * FROM waiters",
  function (err, result) {
     // do something with results here     
  }
);

Which is essentially the same control logic you are trying to build with nodejs. Using the above would eliminate the need for another query.

这与您尝试使用nodejs构建的控制逻辑基本相同。使用上述内容将消除对另一个查询的需要。