La primera consulta a la base de datos de Postgres es una consulta SELECT que obtiene todos los datos de turnos/descansos para el día actual que se utiliza para determinar el tipo de escaneo.
La segunda consulta es una consulta INSERT que depende de los resultados de la primera consulta
Mi función de controlador se ve así en este momento:
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 } Mi problema es que no puedo acceder a los resultados de la primera consulta, ya que parece que la variable shifts tiene un alcance local para la primera Promise.all
** EDIT **Ahora me he dado cuenta de que mi enfoque no era óptimo (solo estaba aprendiendo node-postgres) Una mejor manera de resolver este problema es usar 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 }La variable shifts aún no tendrá un valor cuando se ejecute la declaración if , porque recibe su valor solo en la función .then . Por lo tanto, si la segunda mitad o su código se basan en el valor de shifts , muévalo a la función .then :
.then(function([queryResults]) { shifts = queryResults.rows; if(/* first scan therefore scanning in for shift */) { ... } // else if ... handle all other cases })(Si desea que se ejecuten dos consultas independientes en paralelo, consulte aquí ).