
Promises Don't Run Code in the Background: Async Isn't Parallel
- كاتب موثّق
- ES2025
محتويات المقال
fetch calls in the same handler never froze anything.
The common misconception
async function, it runs in the background, and the page stays responsive until the result comes back.
fetch returns a promise and the page keeps scrolling while the request is in flight. In C#, Task.Run really does hand work to another thread, and async/await look the same in both languages. So "promise" quietly becomes shorthand for "runs somewhere else". The half-truth: the waiting in fetch happens outside JavaScript. Your loop is JavaScript, and it has nowhere else to run.
What actually happens
A promise is a receipt, not a thread
Promise() constructor is explicit: the executor is called synchronously, as soon as the promise is constructed. A loop inside the executor runs right there, on the caller's thread, before the constructor even returns.
async functions run synchronously until the first await
async keyword doesn't change that. MDN puts it plainly: the code of an async function, up to and including the first await, runs synchronously, and an async function without an await runs synchronously from start to finish. What async gives you is a promise as the return value and the ability to pause at an await. Pausing only helps while you wait for something else; while your loop is computing, nothing is paused.
Why fetch doesn't block but your loop does
The export, measured
const start = performance.now();const at = () => `${Math.round(performance.now() - start)} ms`;// Stands in for a click 10 ms after the export startssetTimeout(() => console.log(`click handled at ${at()}`), 10);function sumOfRoots(n) { return new Promise((resolve) => { let total = 0; for (let i = 0; i < n; i++) total += Math.sqrt(i); resolve(total); });}async function exportReport() { await sumOfRoots(300_000_000); console.log(`report ready at ${at()}`);}exportReport();console.log(`exportReport() returned at ${at()}`);// exportReport() returned at 662 ms// report ready at 662 ms// click handled at 662 msconst start = performance.now();const at = () => `${Math.round(performance.now() - start)} ms`;// Stands in for a click 10 ms after the export startssetTimeout(() => console.log(`click handled at ${at()}`), 10);function sumOfRoots(n) { return new Promise((resolve, reject) => { const worker = new Worker("sum-worker.js"); worker.onmessage = (event) => { resolve(event.data); worker.terminate(); }; worker.onerror = reject; worker.postMessage(n); // the loop now runs on the worker's thread });}async function exportReport() { await sumOfRoots(300_000_000); console.log(`report ready at ${at()}`);}exportReport();console.log(`exportReport() returned at ${at()}`);// returned at 1 ms, click handled at 12 ms, report ready at 592 msexportReport() didn't even return for 662 ms, and the click due at 10 ms waited for the whole report. In the right version, the loop runs in a , which MDN describes as a script running in a background thread that can work without interfering with the user interface. exportReport() only posts a message, so it returns at once and the click is handled on time. The worker file is plain computation with no DOM access:
self.onmessage = (event) => { const n = event.data; let total = 0; for (let i = 0; i < n; i++) total += Math.sqrt(i); self.postMessage(total);};Concurrency isn't parallelism
Promise.all doesn't change the picture: it waits for promises that are already running. Three fetches overlap because the waiting happens in the network. But Promise.all([sumOfRoots(a), sumOfRoots(b)]) calls both functions first, each running to completion on the main thread, and only then receives two finished promises. MDN's promise reference spells it out: JavaScript is single-threaded by nature, only one task executes at a given instant, and parallel execution can only be achieved through worker threads.
new Promise(...) | ||
async function | await | |
await null between chunks of work | ||
setTimeout between chunks of work | ||
How to apply it in your project
Find CPU work hiding behind async Look for loops, parsing, sorting, hashing or image processing inside new Promiseexecutors andasyncfunctions. If nothing inside awaits real I/O, the wrapper changes nothing about blocking.Move pure computation to a worker Work that takes data in and returns data, with no DOM access, fits a worker well. Wrap the postMessageround trip in a promise, as above, so callers still justawaitthe result.Slice what must stay on the main thread If the work needs the DOM, split it into small chunks and yield with a task between them, so clicks and paints can run in the gaps. Use Promise.all for waiting, not computing Run independent requests together with Promise.all. For CPU work that should run side by side, start several workers, because only separate threads compute at the same time.
Key takeaways
The Promiseexecutor runs synchronously; wrapping a loop in a promise doesn't move it anywhere.An asyncfunction runs synchronously until its firstawait;asyncnever creates a thread.fetchdoesn't block because the browser does the waiting; your own JavaScript always runs on the main thread.Promise.alloverlaps waiting, not computing. Parallel JavaScript needs a worker.Move pure CPU work to a Web Worker; if it must stay, slice it and yield with a task.
التعليقات (0)