Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
Crear una consulta que se base en los resultados de una consulta anterior usando node-postgres

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 }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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í ).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!