Tips from open-source: Set a maximum time limit on fetch using Promise.race()
This article demonstrates how Promise.race can be used to set a maximum time limit on a fetch request. Originally, I found Promise.race() in the next.js source code.
Promise.race([fetch(EN_URL), timeoutPromise(5000)]) — What this means is that fetch should finish executing in 5 seconds otherwise, it is timed out with a promise rejected.
If the fetch is not resolved in 5 seconds, timeoutPromise rejects and the error is caught in catch block that writes to file with stringified {cn: [], en: [] } as shown above.
Using a promise race solution will leave the request hanging and still consume bandwidth in the background and lower the max allowed concurrent request being made while it’s still in process.
Instead use the AbortController to actually abort the request, Here is an example
const controller = new AbortController()// 5 second timeout:const timeoutId = setTimeout(() => controller.abort(), 5000)fetch(url, { signal: controller.signal }).then(response => { // completed request before timeout fired // If you only wanted to timeout the request, not the response, add: // clearTimeout(timeoutId)})
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.
Usage of Promise.race depends on your usecase. I found that Next.js source code uses Promise.race in an infinite for loop with a breaking condition in a worker related file but I wanted to pick an example that is easy to understand. So, I searched in the wild.
And found a simple, easy to understand example, Promise.race can be used to set a maximum time limit on fetch request but this request fetches the prompts as csv and json in ChatGPT-Next-Web.
However, stackoverflow answer suggests that “Using a promise race solution will leave the request hanging and still consume bandwidth in the background and lower the max allowed concurrent request being made while it’s still in process.”
This makes me conclude that, use Promise.race only if you are fine with the fetch request hanging, otherwise use AbortController to abort the fetch request altogether.