Implementing Custom API timeout using the `Promise.race()` method.
This article demonstrates the implementation of Promise.race() method.

I am software developer, primarily working on the nodejs, graphql, react and mongoDB.
Search for a command to run...
This article demonstrates the implementation of Promise.race() method.

I am software developer, primarily working on the nodejs, graphql, react and mongoDB.
No comments yet. Be the first to comment.
Last time we built a connection pool from scratch. This time: how does a database not lose your data when the power dies? You write a row. The database says OK. A millisecond later, someone trips ove

Nothing is magic — part of a series on building infrastructure primitives from scratch. I used to think request queuing and connection pooling were deep infrastructure magic — something libraries did
A practical guide to pgrx with a real-world data masking example

Why Rust became my favorite language — and how Corrode’s article taught me to enjoy the messy first draft.

A little over a year ago, I got curious about the 1 Billion Row Challenge (1BRC). It seemed like the perfect playground to test Rust’s performance chops — 1 billion weather station measurements, aggregate per-city statistics (min, max, average), and ...
This tutorial is about creating a custom API timeout for your API calls using Promise.race() method.
The Promise.race() the method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.
So, we can provide two inputs inside the race method, i.e:
API call promise.
Delay promise with our custom timeout logic.
Promise.race([apiCall, timeoutFunc])
Here, The apiCall method will represent our API call promise.
// your url
const apiCall = fetch("https://api.github.com/");
and the timeout function will contain the delay logic which will be responsible for throwing a timeout error.
function delay(timeOutPeriod) {
return new Promise((_resolve, reject) => {
setTimeout(() => reject("Request timeout"), timeOutPeriod);
});
}
const timePeriod = 5000;
const timeoutFunc = delay(timePeriod);
So, when we will run the Promise.race method, whichever promise is completed first, will return the output.
Promise.race([apiCall, timeoutFunc])
.then((data) => data.json())
.then((data) => console.log("Data : ", data))
.catch((error) => console.log("Error : "error));
Here, in this particular example, we have provided the custom timeout logic of 5000 milliseconds. So, either the API will give a response with 5 seconds or our network request will get timed out after the 5 seconds.
To check out the code, visit my github link github.