Concurrency in Modern Web Applications
Concurrency allows your application to perform multiple operations simultaneously, improving responsiveness and throughput. Below we explore the most common patterns in JavaScript.
Why Concurrency Matters
- Prevent UI blocking while waiting for network or CPU‑intensive tasks.
- Improve server utilization by parallelizing I/O.
- Enable smoother user experiences on low‑powered devices.
Async/Await – The Modern Approach
Async functions let you write asynchronous code that looks synchronous. Internally they use Promises.
async function fetchData(url) {
const response = await fetch(url);
if (!response.ok) throw new Error('Network error');
const data = await response.json();
return data;
}
Web Workers – Offloading Work From the Main Thread
Web Workers run scripts in background threads.
// main.js
const worker = new Worker('worker.js');
worker.postMessage({cmd:'prime', limit:1e6});
worker.onmessage = e => console.log('Result:', e.data);
// worker.js
self.onmessage = function(e){
if(e.data.cmd==='prime'){
const result = computePrimes(e.data.limit);
self.postMessage(result);
}
};
function computePrimes(limit){
const primes = [];
for(let i=2;i<=limit;i++){
let isPrime=true;
for(let p of primes){
if(p*p>i) break;
if(i%p===0){isPrime=false;break;}
}
if(isPrime) primes.push(i);
}
return primes.length;
}