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.
Create Namespaced Classes with MooTools
MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does. Many developers create their classes as globals which is generally frowned up. I mostly disagree with that stance, but each to their own. In any event…
How I Stopped WordPress Comment Spam
I love almost every part of being a tech blogger: learning, preaching, bantering, researching. The one part about blogging that I absolutely loathe: dealing with SPAM comments. For the past two years, my blog has registered 8,000+ SPAM comments per day. PER DAY. Bloating my database…
JavaScript Copy to Clipboard
“Copy to clipboard” functionality is something we all use dozens of times daily but the client side API around it has always been lacking; some older APIs and browser implementations required a scary “are you sure?”-style dialog before the content would be copied to clipboard — not great for…
Source link