JavaScript Async and Await: A Debugging Guide for Promises, Errors, and Race Conditions
JavaScriptasync awaitpromisesdebuggingweb development

JavaScript Async and Await: A Debugging Guide for Promises, Errors, and Race Conditions

CCodeAcademy Editorial Team
2026-12-03
7 min read

Debug JavaScript async code with a practical checklist for promises, rejected requests, loading states, parallel work, and race conditions.

When JavaScript async code behaves unexpectedly, the cause is usually easier to find once you separate promise state, error handling, execution order, and shared state. This guide provides a reusable debugging checklist for async/await, promise chains, failed requests, loading states, parallel work, and race conditions.

Overview

Asynchronous JavaScript lets a program start work that may finish later, such as requesting data, reading a file, or waiting for a timer. A promise represents that future result. It can be pending, fulfilled, or rejected. The async and await syntax makes promise-based code easier to read, but it does not make the work synchronous or remove the need for error handling.

Start debugging by answering four questions:

  1. Was the asynchronous function called?
  2. Did it return a promise, and was that promise awaited or handled?
  3. Did the operation fulfill or reject?
  4. Can a later operation overwrite, hide, or outlive the result?

Use the browser’s Console and Network panels, a debugger breakpoint, and temporary structured logging rather than adding random console.log() statements. Record an operation identifier, input, start time, completion state, and error where appropriate. This makes timing problems visible without changing the program’s behavior more than necessary.

For request-focused debugging, pair this workflow with a local API testing process such as the one described in How to Test a REST API Locally. For related developer utilities, see Essential Online Developer Tools.

Checklist by scenario

When an async function appears not to run

  • Confirm the function is called on the path you expect. Add a log immediately before the call and another as the first line inside the function.
  • Check event listeners, form handlers, and callbacks for incorrect binding or an early return.
  • Verify that a condition is not preventing the call. Log the condition’s inputs, not only its final result.
  • Check for a synchronous exception before the first await, such as accessing a property on undefined.
  • Confirm the module containing the code loaded successfully and that the browser is executing the latest saved version.

A useful first test is to make the return value explicit:

async function loadUser(id) {
  console.log('loadUser started', { id });
  const response = await fetch(`/api/users/${id}`);
  return response.json();
}

loadUser('42')
  .then(user => console.log('user received', user))
  .catch(error => console.error('user load failed', error));

If the first message appears but the completion messages do not, inspect the promise settlement and the Network panel next.

When a request fails or returns unexpected data

  • Inspect the request URL, method, query parameters, request body, and headers.
  • Check the response status and response body. A completed HTTP request is not automatically a successful application response.
  • With fetch(), explicitly test response.ok or the status code. A server response such as 404 or 500 does not, by itself, reject the fetch promise.
  • Parse the body only once and confirm its format before reading nested properties.
  • Look for network failures, blocked cross-origin requests, authentication problems, timeouts, and aborted requests.
async function getJson(url) {
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`Request failed: ${response.status}`);
  }

  return response.json();
}

try {
  const data = await getJson('/api/items');
  console.log(data);
} catch (error) {
  console.error('Could not load items', error);
}

When errors seem to disappear

An async function always returns a promise. Calling it without awaiting it or attaching a rejection handler can leave a failure disconnected from the code that triggered it.

// The rejection may be unhandled by the caller.
loadUser('42');

// Handle it at the boundary where the operation is started.
loadUser('42').catch(error => {
  console.error('Loading failed', error);
});

Use try/catch around the awaited operation when the current function can recover, display an error, or add useful context. If it cannot handle the error, let it propagate to a higher boundary rather than catching it and doing nothing.

When several operations must run together

Decide whether operations are dependent or independent. Dependent operations should normally be awaited in sequence. Independent operations can often be started together, then coordinated with Promise.all().

const [profile, preferences] = await Promise.all([
  getJson('/api/profile'),
  getJson('/api/preferences')
]);

Remember that Promise.all() rejects when one included promise rejects. If the requirement is to collect every outcome, consider Promise.allSettled() and inspect each result. Do not use parallel execution merely to make code look faster; confirm that the requests are independent and that the server and user experience can handle them.

When results arrive in the wrong order

This is a common JavaScript race condition. For example, a user changes a search term twice. The request for the first term may finish after the second request and overwrite the newer results.

Use an operation token, cancellation, or both. An operation token is simple and framework-neutral:

let latestRequest = 0;

async function search(query) {
  const requestId = ++latestRequest;
  const results = await getJson(`/api/search?q=${encodeURIComponent(query)}`);

  if (requestId !== latestRequest) {
    return; // A newer search has already started.
  }

  renderResults(results);
}

Where supported by the API, an AbortController can cancel work that is no longer relevant. Cancellation is useful, but still validate the result because not every operation responds to cancellation in the same way.

What to double-check

Before changing code, walk through this diagnostic table:

SymptomLikely areaFirst check
No log after an awaitRejected promise or stalled operationInspect the Console, Network panel, and surrounding catch block.
HTTP error reaches success codeMissing response validationCheck response.ok or the status before parsing.
Data is sometimes undefinedShape, timing, or missing returnLog the complete value and verify every branch returns the expected result.
Old data replaces new dataRace conditionTrack request identity and ignore or cancel stale work.
Spinner never stopsIncomplete state cleanupPut cleanup in a finally block.
Several errors appear togetherParallel operations or repeated callsCount invocations and inspect whether work is being duplicated.

Loading state deserves special attention. Set it before starting work, update success or error state after settlement, and always clear it in finally when one operation controls the indicator:

async function refresh() {
  setLoading(true);
  setError(null);

  try {
    const data = await getJson('/api/items');
    renderItems(data);
  } catch (error) {
    setError('Items could not be loaded.');
    console.error(error);
  } finally {
    setLoading(false);
  }
}

Also double-check where state is owned. If two requests can update the same variable, document which result is authoritative. If a component, page, or view can disappear while work is pending, ensure its completion handler cannot update invalid or obsolete UI.

Common mistakes

  • Mixing styles without a reason: Nesting .then() chains inside async/await code can make error flow harder to see. Choose one style per logical section unless interoperation is necessary.
  • Forgetting to return a promise: A callback that starts asynchronous work but does not return it can cause the outer chain to finish too early.
  • Using forEach with await: forEach does not wait for an async callback. Use for...of for sequential work or map to promises and coordinate them explicitly.
  • Catching and hiding errors: An empty catch block removes the evidence needed for diagnosis. Log, rethrow, or convert the error into a clear user-facing state.
  • Assuming timing is a fix: Adding a delay may conceal a race condition without correcting it. Track ownership, cancellation, or operation identity instead.
  • Logging only the final value: Include inputs, request identifiers, status codes, and state transitions so intermittent failures can be compared.
  • Trusting generated fixes without review: AI coding tools can suggest promise rewrites, but verify return values, rejection paths, cancellation behavior, and tests yourself. The AI Coding Assistant Workflow offers a broader review approach.

When to revisit

Return to this checklist whenever you change an API, add caching, introduce parallel requests, modify loading or retry behavior, or move code between browser and server environments. Revisit it before a release if a workflow depends on user navigation, repeated searches, uploads, timers, or rapidly changing input; these are common places for stale results and incomplete cleanup to surface.

When tools, frameworks, or project conventions change, confirm that your debugging steps still match the runtime. Check how requests are represented in the current browser tools, how errors are surfaced by the application framework, and whether the project’s test setup covers rejected promises and out-of-order completion.

Use this final action list before closing an asynchronous bug:

  1. Reproduce the issue with a small, repeatable input.
  2. Log the call, inputs, operation identity, settlement, and error path.
  3. Inspect the actual request and response rather than inferring them from the UI.
  4. Test success, rejection, empty data, slow completion, and repeated calls.
  5. Verify that loading and error state are cleaned up in every path.
  6. Confirm that stale or cancelled work cannot overwrite current state.
  7. Remove noisy temporary logs, retain useful diagnostics, and add a regression test.

A disciplined workflow turns “async JavaScript is not working” into a narrower question about invocation, settlement, data, or ordering. That distinction makes debugging faster and gives future maintainers a clear reason for each promise and state transition.

Related Topics

#JavaScript#async await#promises#debugging#web development
C

CodeAcademy Editorial Team

Developer Resources Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.