الانتقال إلى المحتوى
FrontendJavaScript· 7 دقائق للقراءة

Promises Don't Run Code in the Background: Async Isn't Parallel

A promise lets you wait without blocking, but your own loop still runs on the main thread.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • ES2025
محتويات المقال

The "Export report" button freezes the dashboard: clicks on other buttons are ignored, and the "Preparing…" label shows up only after the report is ready. Last sprint, a developer "made it async": the number-crunching function now returns a promise and the click handler awaits it. The freeze is exactly as long as before, and the team is puzzled, because fetch calls in the same handler never froze anything.

The common misconception

The belief: if CPU-heavy work is wrapped in a Promise or an async function, it runs in the background, and the page stays responsive until the result comes back.

Smart developers believe this because async code really did fix their other freezes. 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

A promise is an object that stands for a result you'll get later. It says nothing about where the work happens. MDN's page on the 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

The 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 browser performs the network request itself, outside your JavaScript. Your code starts it, gets a promise and returns. When the response arrives, the browser settles the promise and your callbacks run on the . MDN describes it as the single thread where, by default, the browser runs all of your page's JavaScript, processes user events and paints. So while your loop runs, clicks and painting wait for it.

The export, measured

The wrong version wraps the loop in a promise. The 10 ms timer stands in for a user's click that arrives while the export is running. Both outputs come from one run in headless Chromium 156:

JavaScript report.js
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 ms

In the wrong version, exportReport() 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:

JavaScript sum-worker.js
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.

What you writeWhere the computation runsCan the page respond meanwhile?
A loop inside new Promise(...)Main thread, synchronouslyNo
A loop inside an async functionMain thread, until the first awaitNo
await null between chunks of workMain thread, resuming as a microtaskNo, microtasks run before input and paint
setTimeout between chunks of workMain thread, in slicesYes, between the slices
A Web WorkerA background threadYes

How to apply it in your project

  1. Find CPU work hiding behind asyncLook for loops, parsing, sorting, hashing or image processing inside new Promise executors and async functions. If nothing inside awaits real I/O, the wrapper changes nothing about blocking.
  2. Move pure computation to a workerWork that takes data in and returns data, with no DOM access, fits a worker well. Wrap the postMessage round trip in a promise, as above, so callers still just await the result.
  3. Slice what must stay on the main threadIf 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.
  4. Use Promise.all for waiting, not computingRun 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 Promise executor runs synchronously; wrapping a loop in a promise doesn't move it anywhere.
  • An async function runs synchronously until its first await; async never creates a thread.
  • fetch doesn't block because the browser does the waiting; your own JavaScript always runs on the main thread.
  • Promise.all overlaps 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.

📚 المصادر

  1. Promise() constructor — MDN
  2. async function — MDN
  3. Promise: Promise concurrency — MDN
  4. Using promises — MDN
  5. Using Web Workers — MDN

التعليقات (0)