Search code examples
javascriptpromisetimeoutcancellation

How to cancel setTimeout if function inside has done processing?


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?


Solution

  • 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)