【发布时间】: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