I want to have function which will do some work, if then is some condition true, then resolve promise. If not, wait little bit (lets say one second) and then try it again. Beside that if time limit expired, promise will reject. How can do I that? Look at my code example...If I wrap entire function in return new Promise(), I cant use await inside of it (which I need...I need to sleep some time if condition fail, and also I need wait to my await at end of my function).
Here is my example of code:
async funcWithTimeLimit(numberToDecrement, timeLimit){
let sleep = undefined;
let timeLimitTimeout = setTimeout(() => {
if (sleep)
clearTimeout(sleep);
return Promise.reject("Time limit of " + (timeLimit/1000) +" secs expired"); //reject
}, timeLimit);
while(numberToDecrement > 0){
for(let i = 10;(i > 0 && numberToDecrement > 0); i--){ //Do some work
numberToDecrement--;
}
if(numberToDecrement > 0){
await new Promise(resolve => sleep = setTimeout(resolve, 1000));
}
}
clearTimeout(timeLimitTimeout);
await new Promise((resolve, reject) => sleep = setTimeout(resolve, 500)); // Do something
return ""; //resolve
}
NOTE: My biggest problem is - how can I write this function to be able to catch rejection (at place where I call funcWithTimeLimit()) in case of time limit expiration?
question from:
https://stackoverflow.com/questions/65871964/how-to-write-an-asynchronous-promise-based-function-that-times-out 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…