Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
Encadenamiento de rechazo de promesas de diferentes archivos js

Tengo un controlador.js desde donde llamo a un método asíncrono en service.js. A pesar de tener un bloque '.catch' para lidiar con el rechazo de Promise, el programa nunca llega allí. SIEMPRE ingresa al bloque '.then' antes de que se resuelva cualquier Promesa.

Aquí está el código para "controller.js" (la persona que llama)

 const Service = require('./service') Service.serviceQueryDB("abc") .then(result => /* Immediately comes here, not waiting for the Promise to be resolved */ console.log("I should have waited, but I'm already here. Resolved : ", result)) .catch(e => /* Never enters this block. The error thrown by Service.serviceQueryDB is never caught because the program runs immediately to the '.then' block */ console.error("Rejected : ", e))

Aquí está el código para "service.js" (el proveedor)

 async function queryDB(str){ return new Promise((_,rej) =>{ setTimeout(()=>{ console.log("Program is on DB now") rej("Query done!") /*I am 'rej'ecting the Promise*/ },1000) }) } async function serviceQueryDB(str){ setTimeout(()=>{ queryDB(str) .then( _ => { return new Promise((res)=>{ res("Query sucessfull") }) }) .catch(e => { /* the Promise rejection from the queryDB() is caught HERE, which is fine */ return new Promise((_,rej) => { console.error(e) /* prints this 'Query done!', which is fine */ rej("Query unsuccessful") /* however, this 'rej'ection is NOT caught in the controller, from where the method is called. Why? */ }) }) }, 1000) } module.exports = {queryDB, serviceQueryDB}

Por lo tanto, la excepción lanzada debe capturarse en el controlador.js y "Consulta fallida" debe imprimirse en el result de la variable aquí: console.log("I should have waited, but I'm already here. Resolved : ", result))

PD: si copia/pega el código en dos archivos separados y ejecuta node .\controller.js , podrá reproducir el error

Gracias por adelantado

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

ok, entonces, estaba buscando a tientas el código, tomé un descanso y tomé un café, y la respuesta es: tengo que señalar inequívocamente que serviceQueryDB() está devolviendo una Promesa

Entonces, si cambio el código en ese método en "service.js" a esto:

 async function serviceQueryDB(str) { return new Promise((res,rej) => { /* have to signal that the return will return a Promise - and that this return is the ONLY possibility of a return value*/ setTimeout(() => { queryDB(str) .then(_ => { res("Query sucessfull") }) .catch(e => { rej("Query unsuccessful") }) }, 1000) }) }

Funciona bien.

Huellas dactilares:

 Program is on DB now Rejected : Query unsuccessful

Todo lo demás se queda igual

about 4 years ago · Santiago Trujillo Denunciar

0

Una forma más mantenible del enfoque del OP...

 const wait = time => new Promise(resolve => setTimeout(resolve, time)); async function serviceQueryDB(str){ return wait(1000) .then(() => { return queryDB(str) }) .then(() => { return res("Query successful"); }); }

Cuando luego decide eliminar las esperas artificiales, hay menos edición...

 async function serviceQueryDB(str){ return queryDB(str) .then(() => { return res("Query successful"); }); }
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda