DEV Community

Cover image for When Promise.race() wasn't racing
Karan
Karan

Posted on

When Promise.race() wasn't racing

The Problem

A week ago we encountered this weird bug in one of our core APIs. The issue was that it was not returning any response whatsoever.

Luckily we’d found this issue during staging. My senior and I immediately got to work. For almost an hour we scratched our heads checking all the edge cases, connections, environments and queries. Everything looked perfectly fine on the command line, so why wasn’t this working?

Annoyed beyond repair, we just decided to take the age old route and decipher each piece of code piece by piece on blocks and queries in the API, until the culprit revealed itself.

Promise.race()

We had initialised a simple check to return a response as soon as the validation service found at least one error in the data that we were validating. Pretty simple use case. We used Promise.race() to achieve this. Promise.race() works perfectly fine when validating lot of data. Again, pretty straightforward answer.

EXCEPT! The function only works on certain conditions.

The BUG

The data that we needed to be validated was being fetched from another query. Apparently when we were passing this data, it was empty and we were unknowingly passing an empty array into the Promise.race([]) function.

This will result in something called a foreverPendingPromise. It’s clearly mentioned in the MDN about this case, and we’d overlooked it.

To understand this situation better, let's dig a little deeper on how the function actually works.

Image description

This results in

Image description

As we see callPromise() took exactly 5 seconds to execute - the fastest getValue() promise to resolve. Works totally fine.

The whole fiasco starts when we pass an empty array. Code pen to Cry - where the console logs `start' and wait forever for the race to finish.

The fix

The simple fix we patched is to run the race only if something in the validation array. It’s a simple problem and a simple solution, but it’s the simplest things that are often neglected. The devil is in the details.


Editing courtesy ah__sho
Code Snippets by Carbon
Cover pic by Austris Augusts on Unsplash

Top comments (0)