How to Set Timeout for a JavaScript Promise
top of page

Subscribe to get best practices, tutorials, and many other cool things directly to your email inbox

  • Writer's pictureAhmed Tarek

How to Set Timeout for a JavaScript Promise

Updated: Apr 17

Just don’t wait forever for a Promise to get fulfilled, you need to set your own terms.


How to Set Timeout for a JavaScript (JS) Promise. Best Practice Code Coding Programming Software Development Architecture Engineering
Image by cherylholt on Pixabay

Did you ever wonder why couldn’t you set a timeout for your JavaScript Promise? You are not alone.


I had the same question before and actually, I couldn’t find an answer for the why. But I eventually decided to stop wondering and start acting.


Implementing a timeout for a JavaScript Promise is not that hard, you can easily do it yourself.


 

This is how I thought things through

  1. The timeout itself could be implemented using the native setTimeout() function.

  2. I can make use of the native Promise.race() function so that I can start a race between the timeout and the original Promise.

  3. This way I can implement the timeout as a Promise by itself.

  4. The remaining part would be about how to integrate the small parts together to get the expected result.


 


 

Implementation


Wait



Here the timeout part is implemented as a Promise by itself. This is done by wrapping the native setTimeout() function into a Promise which would always resolve to the constant string ‘time out’. You can modify this part as it suits your needs, you can even return an object.


PromiseWithTimeout



Here the new Promise functionality is defined as a new object type called PromiseWithTimeout, this way it could be used the same way the native Promise object is used. Therefore, instead of using let myPromise = new Promise(…) you would use let myPromise = new PromiseWithTimeout(…).


The main idea is to use the native Promise.race() function and then return the race promise between the original promise and the wait one we defined.


Using PromiseWithTimeout



Now you can start using the new PromiseWithTimeout easily.


Getting results back from PromiseWithTimeout



Now depending on how you decided to resolve the wait Promise, you can assert the returned result to check if it was a timeout or an actual result of your original Promise.


Finally, hope you found reading this article as interesting as I found writing it.




Recent Posts

See All

Subscribe to get best practices, tutorials, and many other cool things directly to your email inbox

bottom of page
Mastodon Mastodon