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

214
Views
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 answers
Answer question

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 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!