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

209
Vistas
How to wait end of promise but with timeout

I have a REST API coded with Node.js and there is one route that applies NTFS Rights to folders. The request can take 1 second but can also last several minutes (it depends on the size of the folder).

To summarize, if the rights take less than 5 seconds to be applied, I want to return the value with the code 200.

If the rights have not finished being applied I would like to return the value with the code 202

...

inProgress = true;
ApplyRights()
    .then(() => {
        inProgress = false
    }


// Here I want to return as fast inProgress = false otherwise wait a bit but max 5s

return ...;

I tried to wait a bit with setTimeout like this:

const sleep = s => new Promise(resolve => {
    setTimeout(resolve, s * 1000)
});

let nbCheck = 0;
while (inProgress && nbCheck < 5){
    await sleep(1)
    nbCheck++;
}

But setTimeout is not called before the end of my previous promise (ApplyRights). I read here that promise are executed before setTimeout

So, i tried to find a solution without setTimeout and I tried this: (I know it's not very elegant)

let dateStop = Date.now() + 5 * 1000;
while (dateStop = Date.now() && inProgress){}
return ...;

But in this case the .then() of ApplyRights is only reached at the end of the 5s.

Is there a way to let my promise ApplyRights do its job. And if the job take time, wait maximum 5 seconds before returning the response. If the job is quick, I want to return the responses without waiting.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use Promise.race:

Promise.race([ApplyRights(), sleep(5)]).then(result => {
    if (result === undefined) { // Timeout of 5 seconds occurred 
         // Some message to the user?
    } else { // Got reply within 5 seconds
         // Do something with the result
    }
});

Do realise however, that this does not interrupt the work of ApplyRights(), which eventually may still do the job.

about 4 years ago · Juan Pablo Isaza 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