My account

Asynchronous JavaScript

The browser runs JavaScript on one thread, and the event loop decides what runs after the synchronous code. First all microtasks (like promise callbacks), then one task (like setTimeout). This lesson shows promises, async and await, running work in parallel, fetch errors and cancelling requests with AbortController, using the online shop example.

Not reviewedWritten with AI helpReading time: 17 minOnline shop exampleJavaScript codeLive example

Author: bezzad

Contents

The problem: a page that freezes and answers that arrive out of order

Our online shop has four bug reports:

  1. A user clicks “Apply filters” and the page freezes for two seconds. No button works.
  2. A user types “phone” in the search box, but sees the results for “ph”.
  3. The checkout page shows “Order placed”, while the server returned a 500 error.
  4. The cart page sends three requests one after another and opens slowly.

All four bugs come from one place: we do not know exactly when and in what order async code runs.

One thread and the event loop

The browser runs the page’s JavaScript on one main thread. The same thread answers clicks and draws the page. So only one thing happens at a time.

  1. The call stack is the function running now, plus the functions that called it.
  2. Waiting work like timers, network requests and clicks is tracked by the browser itself, outside JavaScript. When it is ready, its callback waits in a queue.
  3. The task queue (or macrotask queue) is for setTimeout callbacks, events like clicks, and messages.
  4. The microtask queue is for promise callbacks (then, catch, finally, and the rest of a function after await) and the queueMicrotask function.

The event loop repeats these steps:

  1. Take one task from the task queue and run it to the end, until the call stack is empty.
  2. Run all microtasks. If a microtask adds a new microtask, that one also runs now.
  3. The browser may draw the page (render). This happens at most once per frame, not after every task.
  4. Go back to step one.
Call stackruns one thing at a timeconsole.logscriptMicrotask queueall of them runthen(callback)queueMicrotask(callback)Task queueone per loopsetTimeout(callback)click handler1. One task2. All microtasks3. Maybe render the pagerepeat
First the synchronous code runs to the end. Then all microtasks. Then the browser may draw the page. Then the next task.

Why does the page freeze?

The browser does not draw the page or answer a click in the middle of a task. If filtering 50,000 products takes two seconds, the page is dead for two seconds. A task that takes longer than 50 ms is called a long task.

The fix: split the work into pieces and give the browser a chance between them:

function yieldToBrowser() {
  return new Promise((resolve) => setTimeout(resolve, 0));
}

async function filterInChunks(products, test) {
  const result = [];
  for (let i = 0; i < products.length; i += 500) {
    result.push(...products.slice(i, i + 500).filter(test));
    await yieldToBrowser(); // the browser can handle clicks and paint here
  }
  return result;
}
  1. Each piece is a short task.
  2. The setTimeout function sends the rest of the work to a new task. Between two tasks, the browser can answer clicks and draw the page.
  3. A plain promise would not work here. The rest of the work would be a microtask, and it would run before rendering.
  4. For very heavy work (for example, processing a big file) use a Web Worker. A worker runs on another thread.

The order of execution

What does this code print?

console.log('1: sync');
setTimeout(() => console.log('5: timeout'), 0);
Promise.resolve()
  .then(() => console.log('3: first then'))
  .then(() => console.log('4: second then'));
console.log('2: sync');
1: sync
2: sync
3: first then
4: second then
5: timeout
  1. The synchronous code runs first, to the end: 1 and 2.
  2. Then all microtasks: the first then (3). When it finishes, the second then enters the microtask queue and also runs now (4).
  3. Last of all, the timer task (5). Zero in setTimeout means “the earliest possible task”, not “right now”.
Live example: the event loop step by step
console.log('1: sync');setTimeout(() => console.log('5: timeout'), 0);Promise.resolve()  .then(() => console.log('3: first then'))  .then(() => console.log('4: second then'));console.log('2: sync');

Call stack
    Microtask queue
      Task queue
        Console output

          Promises

          A promise is a result that arrives later. It has three states:

          1. Pending: still waiting.
          2. Fulfilled: finished with a value.
          3. Rejected: finished with an error.

          Once a promise is finished (settled), its state never changes again.

          loadProduct(7)
            .then((product) => loadReviews(product.id)) // returns a promise: the chain waits for it
            .then((reviews) => renderReviews(reviews))
            .catch((error) => showError('Could not load reviews.'))
            .finally(() => hideSpinner());
          1. The then method always returns a new promise. That is why you can chain them.
          2. If the callback returns a promise, the next step waits for it. If it returns a value, that value goes to the next step.
          3. One catch at the end catches the error of any earlier step.
          4. The finally method runs in both cases. It is a good place to hide the spinner.
          5. A common mistake: if you create a promise inside then and do not return it, the chain does not wait for it, and its error does not reach catch.

          The async and await keywords

          The same work with async and await reads like normal code:

          async function showProduct(id) {
            showSpinner();
            try {
              const res = await fetch(`/api/products/${id}`);
              if (!res.ok) throw new Error(`HTTP ${res.status}`);
              const product = await res.json();
              renderProduct(product);
            } catch (error) {
              showError('Could not load the product.');
            } finally {
              hideSpinner();
            }
          }
          1. An async function always returns a promise.
          2. The await keyword pauses only this function, not the thread. The rest of the page keeps working. The rest of the function runs later as a microtask.
          3. An error from an await reaches catch like a normal error.
          4. If nobody catches a promise’s error, the browser shows an “unhandled rejection” error in the console, and the user sees no message.

          The fetch function does not reject on 404 and 500

          This is the checkout page bug:

          1. The fetch function rejects only when no response arrives at all: the network is down, a CORS error, or the request was cancelled.
          2. A 404 or 500 response is still a response. So the promise is fulfilled.
          3. The ok property is true only for status codes 200 to 299. Always check it, like the code above.
          4. The json method also returns a promise, and it throws if the body is not JSON.

          Running in parallel

          The cart page needs three pieces of data that do not depend on each other:

          // Slow: each request starts after the previous one ends
          async function loadCartPageSlow() {
            const user = await getUser();
            const cart = await getCart();
            const offers = await getOffers();
            return { user, cart, offers };
          }
          
          // Fast: all three start together
          async function loadCartPage() {
            const [user, cart, offers] = await Promise.all([getUser(), getCart(), getOffers()]);
            return { user, cart, offers };
          }
          One after anothergetUser()getCart()getOffers()900 msTogethergetUser()getCart()getOffers()300 mstime
          With three awaits in a row, the times add up. With Promise.all the requests start together, and the total time is about the time of the slowest one.
          Method When does it finish? Use in the shop
          The Promise.all method When all succeed. It rejects on the first error. A page that makes no sense without all its data.
          The Promise.allSettled method When all finish. It never rejects. Each result has a status. Home page widgets. If one fails, show the others.
          The Promise.race method When the first one finishes, success or failure. Building a manual timeout.
          The Promise.any method When the first one succeeds. If all fail, an AggregateError. Getting a file from several servers.
          The Promise.all method does not cancel. When one request fails, Promise.all rejects right away. But the other requests are still running. If you must stop them, use an AbortController.

          The trap: await in a loop and forEach with async

          A user wants to empty the cart. Each product needs a delete request:

          // 1. Sequential: each request waits for the previous one
          for (const id of ids) {
            await removeFromCart(id);
          }
          
          // 2. Wrong: forEach does not wait for async callbacks
          ids.forEach(async (id) => {
            await removeFromCart(id);
          });
          showMessage('Cart is empty'); // runs before any request finishes
          
          // 3. Parallel, and we wait for all of them
          await Promise.all(ids.map((id) => removeFromCart(id)));
          showMessage('Cart is empty');
          1. A for…of loop with await is correct, but sequential. You want it when the order matters, or when you do not want to flood the server with requests.
          2. The forEach method ignores the promises the callback returns. The code after it runs right away. Errors also reach no catch.
          3. The map method with Promise.all starts them all together and waits for all of them.

          Cancelling requests and stale responses

          Look at the search box bug step by step:

          1. The user types “ph”. Request A goes out. This search has many products and is slow.
          2. The user types “phone”. Request B goes out and comes back fast. The right results are shown.
          3. Request A arrives later and writes the old results over the right ones.
          BrowserServerSlow search?q=ph?q=phoneresults for phoneRight resultresults for phStale resultover the right one
          Responses do not have to arrive in the order of the requests. The stale response arrives last and breaks the right result.

          The fix: before each new search, cancel the previous request with an AbortController:

          let controller = null;
          
          async function searchProducts(text) {
            controller?.abort(); // cancel the previous request
            controller = new AbortController();
            try {
              const res = await fetch(`/api/search?q=${encodeURIComponent(text)}`, {
                signal: controller.signal,
              });
              if (!res.ok) throw new Error(`HTTP ${res.status}`);
              renderResults(await res.json());
            } catch (error) {
              if (error.name === 'AbortError') return; // we cancelled it: not a real error
              showError('Search failed.');
            }
          }
          1. The abort method makes the previous request’s promise reject with an AbortError. So it never reaches renderResults.
          2. Handle AbortError separately. It is not a real error and should not show an error message.
          3. For a timeout, you can pass the AbortSignal.timeout function a time in milliseconds. Then the error is named TimeoutError.
          4. Cancelling is only on the browser side. The server may have already received and done the request. So cancelling a “place order” request means “I stop waiting for the answer”, not “the order was not placed”.
          5. Combine this with debounce, so not every letter sends a request.

          Common mistakes

          Mistake Result Better way
          A heavy loop on the main thread The page freezes. Clicks get no answer. Split the work, or use a Web Worker.
          Thinking setTimeout with zero means right now Wrong order of execution. First sync code, then microtasks, then a task.
          Not reading the ok property after fetch A 500 error is shown as success. If ok is false, throw an error.
          Several awaits in a row for independent work The page opens slowly. The Promise.all method.
          The forEach method with an async callback The next code runs too early. Errors are lost. A for…of loop, or map with Promise.all.
          Forgetting return inside then The chain does not wait. Always return the promise, or use await.
          Search without cancelling the previous request A stale response breaks the right result. Use an AbortController.
          Showing an error for AbortError A fake error message for the user. Handle AbortError separately.

          Summary in seven lines

          1. The page’s JavaScript runs on one thread. A long task freezes the page.
          2. The event loop order: one task, then all microtasks, then maybe a render, then the next task.
          3. Promise callbacks and the rest of a function after await go to the microtask queue. The setTimeout function and events go to the task queue.
          4. The await keyword pauses only its own function. Catch errors with try and catch.
          5. The fetch function does not reject for 404 and 500. Always check the ok property.
          6. Run independent work together with Promise.all or allSettled. The forEach method does not wait for async.
          7. Cancel the previous search request with an AbortController, so a stale response cannot break the result.

          Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.