【问题标题】:Creating a query that relies on results of previous query using node-postgres使用 node-postgres 创建依赖于先前查询结果的查询
【发布时间】:2021-12-14 17:20:49
【问题描述】:

对 postgres 数据库的第一个查询是 SELECT 查询获取当天用于确定扫描类型的所有班次/休息数据

第二个查询是一个INSERT 查询,它依赖于第一个查询的结果

我的处理函数现在看起来像这样:

const scanEvent = (request, response) => {
   employee_id = request.body.employee_id;
   var shifts;
   Promise.all([
      pool.query('Select * FROM shifts WHERE employee_id=$1 AND date=CURRENT_DATE', [employee_id])
   ]).then(function([queryResults]) {
      shifts = queryResults.rows;
   }).catch(function(e) {
      response.status(500).send('Error retrieving data');
   })
   // based on the results of the query there will be a bunch of different cases for
   // INSERT queries to put in the proper data to the database
   if(shifts.length == 0) {
      Promise.all([
         pool.query('INSERT INTO shifts (employee_id, start_time) VALUES ($1, NOW())', [employee_id])
      ]).then(function() {
         response.status(204).send('Successfully Inserted');
      }).catch(function (e) {
         response.status(500).send("Error");
      });
    } // else if ... handle all other cases
}

我的问题是我无法访问第一个查询的结果,因为似乎shifts 变量在第一个Promise.all 的范围内是本地的

** EDIT **

我现在意识到我的方法不是最优的(只是学习 node-postgres)解决这个问题的更好方法是使用 async / await:

const scanEvent = async (request, response) => {
   employee_id = request.body.employee_id;
   var shifts;

   const getShifts = await pool.query('Select * FROM shifts WHERE employee_id=$1 AND date=CURRENT_DATE', [employee_id]);

   shifts = getShifts.rows;

   // based on the results of the query there will be a bunch of different cases for
   // INSERT queries to put in the proper data to the database
   if(shifts.length == 0) {
      await pool.query('INSERT INTO shifts (employee_id, start_time) VALUES ($1, NOW())', [employee_id]);

    } // else if ... handle all other cases
}

【问题讨论】:

  • 你为什么只用一个 Promise 来使用 Promise.all?
  • @madflow 我现在已经意识到仅使用一个 Promise 的 Promise.all 是毫无意义的,当我学习 node-postgres 时,这就是我看到查询的方式,所以我就是这样做的跨度>

标签: javascript node.js express node-postgres


【解决方案1】:

if 语句执行时,变量shifts还没有有值,因为它只在.then 函数中接收它的值。因此,如果后半部分或您的代码依赖于shifts 的值,请将其移至.then 函数中:

.then(function([queryResults]) {
  shifts = queryResults.rows;
  if(/* first scan therefore scanning in for shift */) {
    ...
  } // else if ... handle all other cases
})

(如果您想并行执行两个独立的查询,请参阅here。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 2020-02-03
    • 2020-05-19
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    相关资源
    最近更新 更多