Did you know about Promise.race ?
Today, I faced a time-sensitive problem.
The task was simple: I had to call an API, but the call needed to be completed within 500 milliseconds. If it took any longer, I had to return a “Timeout” response.
My first instinct was to track the time by recording the start time of the API call and calculating the time difference once the call was completed.
Based on that, I could decide whether to return the API’s response or a “Timeout” message.
This approach seemed reasonable at first, but after some research, I found a much better and more efficient way to solve this problem using a built-in JavaScript function called Promise.race
.
What is Promise.race
?
Promise.race
is a powerful method that allows you to run multiple promises simultaneously and returns the result of the first one to complete—whether it's a success or a failure.
This behavior is perfect for handling timeouts in API calls.
Instead of manually calculating how long the call takes, you can "race" the API call against a timer.
Whichever finishes first dictates the result.
Let me show you how it works.