A few years back I wrote a blog post about how write a fetch
Promise that times out. The function was effective but the code wasn’t great, mostly because AbortController
, which allows you to cancel a fetch Promise, did not yet exist. With AbortController
and AbortSignal
available, let’s create a better JavaScript function for fetching with a timeout:
Much like the original function, we’ll use setTimeout
to time to the cancellation but we’ll use the signal
with the fetch
request:
async function fetchWithTimeout(url, opts = {}, timeout = 5000) { // Create the AbortController instance, get AbortSignal const abortController = new AbortController(); const { signal } = abortController; // Make the fetch request const _fetchPromise = fetch(url, { ...opts, signal, }); // Start the timer const timer = setTimeout(() => abortController.abort(), timeout); // Await the fetch with a catch in case it's aborted which signals an error try { const result = await _fetchPromise; clearTimeout(timer); return result; } catch (e) { clearTimeout(timer); throw e; } }; // Usage try { const impatientFetch = await fetchWithTimeout('/', {}, 2000); } catch(e) { console.log("fetch possibly canceled!", e); }
The JavaScript code above is much cleaner now that we have a proper API to cancel fetch
Promise calls. Attaching the signal
to the fetch request allows us to use a setTimeout
with abort
to cancel the request after a given amount of time.
It’s been excellent seeing AbortController
, AbortSignal
, and fetch
evolve to make async
requests more controllable without drastically changing the API.
7 Essential JavaScript Functions
I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like
addEventListener
andattachEvent
. Times have changed but there are still a few functions each developer should…Introducing MooTools Templated
One major problem with creating UI components with the MooTools JavaScript framework is that there isn’t a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven…
jQuery Chosen Plugin
Without a doubt, my least favorite form element is the
SELECT
element. The element is almost unstylable, looks different across platforms, has had inconsistent value access, and disaster that is the result ofmultiple=true
is, well, a disaster. Needless to say, whenever a developer goes…MooTools onLoad SmoothScrolling
SmoothScroll is a fantastic MooTools plugin but smooth scrolling only occurs when the anchor is on the same page. Making SmoothScroll work across pages is as easy as a few extra line of MooTools and a querystring variable. The MooTools / PHP Of course, this is a…