0

I have a function A which performs some processing

A().then({  
    check if error saveStatus(failure) 
    if not then saveStatus(Success)
});  

I want to add a timeout for the above function, so that if it has written status then it should be timed out else if success/failure none is written to DB further action can be taken.

Is there any way I can know that function A processing saveStatus() and cancel the timeout at the same instant?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
developer
  • 31
  • 1
  • 11

1 Answers1

0

Yes, you can use this:

function PromiseTimeout(promise, ms) {
  let timeout;
  return Promise.race([
      promise,
      new Promise((_, reject) => {
         timeout = setTimeout(() => reject(new Error('timeout')), ms)
      })
  ]).then(x => { clearTimeout(timeout); return x });
}

This snippet is extracted from open source code I've written time ago.

So, if you have a promise that you want to timeout, you can use it like this:

PromiseTimeout(A(), 1000) // 1 sec timeout
.then(() => everything ok and not timeout)
.catch((err) => maybe error maybe timeout)
lilezek
  • 6,976
  • 1
  • 27
  • 45
  • 1
    There's no reason to make the function `async` when you return a new promise and don't use `await` anywhere. Also I would recommend [`.then(…, …)` over `.then(…).catch(…)`](https://stackoverflow.com/q/24662289/1048572), and you might want to avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it) and use `Promise.race` instead (wrapping only the `setTimeout` in the `new Promise`). – Bergi Nov 05 '17 at 22:38
  • @Bergi, may you like to make a proposal avoiding the antipattern? – lilezek Nov 05 '17 at 22:41
  • Similar to [this code](https://stackoverflow.com/a/37120577/1048572), just add `.then(x => { clearTimeout(…); return x })` to the `promise` – Bergi Nov 05 '17 at 22:52
  • @lilezek Promises worked. But it goes in catch first perform the task inside catch() within 2-3 sec instead of waiting for whole 30 secs and then executes A() and overwrites the status – developer Nov 06 '17 at 00:25
  • @Bergi edited with your suggestions. Is that what you tipped for? – lilezek Nov 07 '17 at 18:10