Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
Try/Catch en múltiples esperas en la aplicación express

Estoy haciendo algunas llamadas a la base de datos y estoy usando async/await y try/catch para el manejo de errores. Estoy luchando si debo tener todas las llamadas de db en un try/catch, or have multiple bloques de prueba/captura para cada llamada.

También tengo algunas llamadas en callback fncs, no estoy seguro de que esas llamadas se atrapen en mi bloque catch si solo tengo un try/catch . Con eso en mente, esas llamadas tienen su propio bloque try catch. Aquí hay un ejemplo de trabajo:

 exports.syncStaff = async function (req, res, next) { // ShiftTask && Shift is a model from mongoose try { // DB CALL #1 --> Inside of Try/Catch Block const shift = await Shift.findById(req.params.id); // DB CALL #2 + 3 --> Two calls run in parallel --> Inside of Try/Catch Block const [shiftTasks, shiftType] = await Promise.all([ ShiftTask.find({ group: shift.id }), mongoose.model('ShiftType').findById(shift.type).populate('tasks').select('tasks') ]); await Promise.all(shiftTasks.filter(st => !shiftType.workshops.find(type => type.id.toString() === st.task.toString() || st.status !== 'pending')).map(task => { // DB CALL #4 --> Separate Try/Catch Block, is this needed? try { return ShiftTask.remove({ _id: task.id }); } catch (error) { console.error(error); next(error); } })); await Promise.all(shiftType.workshops.filter(type => !shiftTasks.find(task => task.shift.toString() === type.id.toString())).map(type => { try { // DB CALL #5 -- Separate Try/Catch Block, is this needed? return ShiftTask.create({ group: shift.id, eventType: type.id }); } catch (error) { console.error(error); next(error); } })); return await res.status(201).json('still to be decided'); } catch (error) { console.error(error); next(error); } };

¿Son necesarios los bloques try/catch en las llamadas db #4 y #5?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

No creo que se necesiten bloques de captura de prueba externos. Si se arroja un error desde algún lugar, se puede capturar desde el bloque en el contenedor público. Hice un ejemplo como este. Puede probar el segundo caso especificado en el código de la consola de Google Chrome.

 let compPromise = new Promise(function(resolve, reject) { resolve('Complete'); }); let errPromise = new Promise(function(resolve, reject) { reject(new Error("Whoops promise reject!")) }); let exec = async () => { try { let res1 = await compPromise; console.log('res1', res1); let [res2,res3] = await Promise.all([ compPromise, compPromise ]) console.log('res2', res2); console.log('res3', res3); // In this case, reject will return from the promise and will catch it in the catch block. await Promise.all([10, 20, 30].map((x) => x === 30 ? errPromise : compPromise)) // In this case, the parameter was deliberately sent as undefined and will still be caught in the catch block. await Promise.all([undefined, 'Johnny', 'Alison'].map((x) => x.trim().includes("n") ? errPromise : compPromise)) } catch(err) { console.log(err.toString()); } } exec()

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda