Loading Thucde.dev
Preparing the next view.
Promise.race. Let me show you how.Promise.race method is introduced in ECMAScript 2015 (ES6). This means any JavaScript engine that supports ES6 or later versions will have built-in support for Promise.race. Promise.race is a method provided by the Promise object in JavaScript. It takes an iterable of promises (like an array) as input and returns a new promise. This new promise settles (either resolves or rejects) as soon as one of the promises in the iterable settles.timeout.export const timeout = function (sec) { return new Promise(function (_, reject) { setTimeout(function () { reject(new Error('Request took too long!')); }, sec * 1000); }); };
The timeout function
timeout function call inside an array in Promise.race, as follow:const res = await Promise.race([ axios.post(ENDPOINT_URL, requestBody), timeout(20) ]);
In this example, the request will timeout after 20s
Promise.race will return immediately after either the axios.post finishes its operation or the timeout occurs. This way, you can proactively control the timeout period for your request, ensuring it won't take too long to respond.AbortSignal.timeout(millisecond) as a signal in the axios request. Like so:axios.get('/foo/bar', { signal: AbortSignal.timeout(5000) //Aborts request after 5 seconds }).then(function(response) { //... });
Example of using AbortSignal.timeout with Axios. Source: Axios document.
function newAbortSignal(timeoutMs) { const abortController = new AbortController(); setTimeout(() => abortController.abort(), timeoutMs || 0); return abortController.signal; } axios.get('/foo/bar', { signal: newAbortSignal(5000) //Aborts request after 5 seconds }).then(function(response) { //... });
Example of using helper function as a signal in Axios. Source: Axios document.
fetch request, not just axios.