How to Set Timeout for a JavaScript Promise

How to Set Timeout for a JavaScript Promise

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

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.

How to Set Timeout for a JavaScript Promise

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.

How to Set Timeout for a JavaScript Promise

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.

How to Set Timeout for a JavaScript Promise

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.

How to Set Timeout for a JavaScript Promise

Using PromiseWithTimeout

Now you can start using the new PromiseWithTimeout easily.

How to Set Timeout for a JavaScript Promise

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.

How to Set Timeout for a JavaScript Promise

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

This article is originally published on Development Simply Put.