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

251
Views
En NodeJS, ¿puedo crear una promesa y detectar su falla más tarde?

Estoy escribiendo un código que toma algún resultado de forma asincrónica y lo almacena hasta más tarde, cuando otra función lo necesita, algo así como ansioso por cargarlo. (En mi caso específico, estoy obteniendo un secreto del administrador de AWS Secrets, pero lo que sea). Mi código se ve así:

 const secretPromise = new Promise((resolve, reject) => { try { const credentialsJSON = await new AWSController().getSecret("my-credentials"); resolve(JSON.parse(credentialsJSON)); } catch (e) { reject(new Error(`Error getting credentials: ${e.message}`)); } }); // in an expressJS route handler: router.get("/groups", async (request, response) => { try { const credentials = await secretPromise; const result = await doSomething(credentials); response.send(JSON.stringify(result)); } catch (error){ response.status(503).send(`Error: ${error.message)`); } });

Lo que no me di cuenta fue que si no hay un controlador para esta promesa, generará un error y bloqueará mi código nodeJS de inmediato. ¿Hay alguna manera de almacenar el resultado o el error y manejarlo más tarde? No quiero que mi servidor se bloquee solo porque una función API no funcionará.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

La secretPromise antes, fuera del controlador de ruta. Por lo tanto, puede ser rechazado antes de que se llame al controlador de ruta, cuando no hay un bloque try-catch que atrape ese rechazo.

Una secretPromise rechazada hace que cada solicitud GET /groups posterior falle, podría manejar esto sin un rechazo:

 const secretPromise = new Promise((resolve, reject) => { try { const credentialsJSON = await new AWSController().getSecret("my-credentials"); resolve(JSON.parse(credentialsJSON)); } catch (e) { resolve({error: new Error(`Error getting credentials: ${e.message}`)}); } }); // in an expressJS route handler: router.get("/groups", async (request, response) => { try { const credentials = await secretPromise; if (secretPromise.error) throw secretPromise.error; const result = await doSomething(credentials); response.send(JSON.stringify(result)); } catch (error){ response.status(503).send(`Error: ${error.message)`); } });
over 4 years ago · Santiago Trujillo Report

0

La espera dentro de secretPromise no está dentro de una función asíncrona, por lo tanto, el código no es válido. Además, no hay necesidad de envolverlo en una Promesa.

Para obtener con entusiasmo las credenciales antes de que se llame a la API, simplemente lo escribiría así:

 let credentials; try { const credentialsJSON = await new AWSController().getSecret("my-credentials"); credentials = JSON.parse(credentialsJSON); } catch (e) { credentials = new Error(`Error getting credentials: ${e.message}`); } }; // in an expressJS route handler: router.get("/groups", async (request, response) => { try { if (credentials instanceof Error) { throw credentials; } const result = await doSomething(credentials); response.send(JSON.stringify(result)); } catch (error){ response.status(503).send(`Error: ${error.message)`); } });
over 4 years ago · Santiago Trujillo 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!