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.
This is how I thought things through
- The timeout itself could be implemented using the native
- I can make use of the native
Promise.race()function so that I can start a race between the timeout and the original Promise.
- This way I can implement the timeout as a Promise by itself.
- The remaining part would be about how to integrate the small parts together to get the expected result.
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.
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.
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 story as interesting as I found writing it.
This article is originally published here.