1

I have read many different ways of adding timeouts within a promise, but most, if not all, seem to utilise the setTimeout() method. By definition:

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

What I am looking for is a way to say:

"If the function executed inside the promise (that will either resolve or
reject the promise), does not complete within a specified x number of
milliseconds, automatically reject or raise an exception."

If this is the same as the defined above (using the setTimeout() method), an explanation would be highly appreciated!

Mario
  • 339
  • 4
  • 17
  • 1
    See also [Timeout in async/await](https://stackoverflow.com/q/37120240/1048572) and [Timeout a Promise if failed to complete in time](https://stackoverflow.com/q/32461271/1048572) – Bergi Nov 13 '20 at 13:32

1 Answers1

10

You can wrap setTimeout in a Promise and create a little "wait"-function which you can then use with Promise.race:

function wait(ms) {
   return new Promise((_, reject) => {
      setTimeout(() => reject(new Error('timeout succeeded')), ms);
   });
}

try {
  const result = await Promise.race([wait(1000), yourAsyncFunction()]);
} catch(err) {
  console.log(err);
} 

With this code Promise.race will reject if yourAsyncFunction takes longer than 1000 ms to resolve/reject, otherwise result will yield the resolved value from yourAsyncFunction.

eol
  • 23,236
  • 5
  • 46
  • 64
  • If I only have one Promise function, would something like: ` function() { return new Promise( (res, rej) => { setTimeout(() => { return rej(new Error("Timed out!")); }); return asyncFunction(){} .then((data) => { return res(data); }) .catch((err) => { return rej(err); }); ` – Mario Nov 13 '20 at 13:18
  • Sorry, not fully sure how to properly comment a code block in the comment section of StackOverflow.. – Mario Nov 13 '20 at 13:24
  • You mean how you can use my code in a function? – eol Nov 13 '20 at 13:33
  • Along those lines yes. To my understanding, your code creates a separate promise to my function and then if my function does not complete faster than the promise you created, the rejection is executed first? – Mario Nov 13 '20 at 13:35
  • 1
    Yes, I think overall this can be used as a general guideline and I might tweak it just a bit to suit my needs. Thank you! – Mario Nov 13 '20 at 13:43