Sankalp Mishra’s Post

Day 99 of me reading random and basic but important dev topicsss.... Today I read about the Scaling Cancellations in JavaScript..... Yesterday, I read how to cancel a single fetch() request using AbortController to prevent memory leaks and UI bugs. But what if we're building a complex dashboard loading dozens of widgets simultaneously? Good news is AbortController is highly scalable.... You don’t need to instantiate a new controller for every single request. A single AbortController signal can be passed to multiple fetch calls. If the user hits "Cancel" or navigates away, calling controller.abort() once will instantly kill all associated network requests! const controller = new AbortController(); const urls = ['/api/users', '/api/analytics', '/api/settings']; // Map URLs to fetch promises, all sharing the same exact signal const fetchJobs = urls.map(url => fetch(url, { signal: controller.signal }) ); try { const results = await Promise.all(fetchJobs); console.log("All data loaded successfully!"); } catch (err) { if (err.name === 'AbortError') { console.log(" ALL parallel requests were aborted instantly!"); } } // Call this from anywhere in your app to cancel everything: // controller.abort(); Note: It's not just for fetch...... You don't have to limit yourself to network requests. AbortController is an elegant, universal event bus for cancellation. You can integrate it into your own custom asynchronous tasks. Since controller.signal emits a standard event, all you need to do is listen for the 'abort' event within your custom Promise: const ourCustomJob = new Promise((resolve, reject) => { // ... Heavy background task logic here ... // Tie your custom task to the same controller controller.signal.addEventListener('abort', () => { reject(new Error("Custom Job Aborted!")); }); }); // Now Promise.all([ ...fetchJobs, ourCustomJob ]) can ALL be managed together! By standardizing cancellation across your app using AbortController, you ensure clean garbage collection, eliminate race conditions, and drastically save your users' network bandwidth. Keep Learning!!!! #JavaScript #AsyncProgramming #WebDev #SoftwareEngineering #CleanCodee

  • diagram, schematic

To view or add a comment, sign in

Explore content categories