Home > OS >  How to wait end of promise but with timeout
How to wait end of promise but with timeout

Time:05-05

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.

Any help would be very appreciated.

CodePudding user response:

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.

  • Related