JavaScript Async Workflows That Fail Safely: Timeouts, Cancellation and Concurrency

Tim Rabbetts | November 21, 2026

Asynchronous JavaScript is easy to start and surprisingly easy to get wrong. A function calls fetch(), awaits a response and updates the interface. The code looks tidy, but real applications have to cope with slow servers, users navigating away, duplicate clicks, rate limits, partial failures and requests that finish after the state they were meant to update has disappeared.

Reliable async code is not just about using async and await. It needs an explicit policy for how work starts, how long it may run, what happens when it is no longer needed, how many operations may run at once and which failures should stop the workflow.

This article develops that policy around a reusable JavaScript pattern. The examples use browser APIs, but the ideas also apply to Node.js services, command-line tools and background jobs.

Start by defining the lifecycle

Before writing a promise chain, describe the operation in terms of its lifecycle:

  • Created: the application decides that work is required.
  • Started: the operation begins consuming resources, such as a connection or queue slot.
  • Completed: a usable result is available.
  • Failed: the operation cannot produce a result.
  • Cancelled: the caller no longer wants the result.
  • Timed out: the operation exceeded its agreed deadline.

These outcomes should not be silently treated as the same thing. A user cancelling a search because they typed another character is normal control flow. A server returning HTTP 500 may be worth retrying. A timeout may require a slower fallback or a visible warning. Treating all three as “something went wrong” makes both the user experience and the logs less useful.

JavaScript promises provide composition tools such as Promise.all(), Promise.allSettled(), Promise.any() and Promise.race(). They do not, by themselves, cancel the underlying work. The MDN promises guide also notes that an await pauses only the surrounding async function; it does not block the entire JavaScript program.

Use a signal for cancellation

The standard way to make fetch-based work cancellable is AbortController. Create one controller for the operation, pass its signal to every API that supports it, and call abort() when the work is no longer wanted.

async function loadUser(userId, signal) {
  const response = await fetch(`/api/users/${userId}`, { signal });

  if (!response.ok) {
    throw new Error(`User request failed with ${response.status}`);
  }

  return response.json();
}

const controller = new AbortController();

const promise = loadUser(42, controller.signal);

// Later, perhaps when the component is removed:
controller.abort();

try {
  const user = await promise;
  console.log(user);
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('The request was cancelled');
  } else {
    throw error;
  }
}

A signal is best treated as an input to a function, rather than something hidden in global state. That makes the function easier to test and allows a caller to decide when its work is obsolete.

Pass the same signal through your own layers where appropriate:

async function loadDashboard(signal) {
  const response = await fetch('/api/dashboard', { signal });

  if (!response.ok) {
    throw new Error(`Dashboard request failed with ${response.status}`);
  }

  const dashboard = await response.json();

  return {
    dashboard,
    recommendations: await loadRecommendations(dashboard.userId, signal)
  };
}

async function loadRecommendations(userId, signal) {
  const response = await fetch(`/api/users/${userId}/recommendations`, {
    signal
  });

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

  return response.json();
}

Do not catch an abort merely to log it as an application error. In a type-ahead search, cancellation is expected every time the user enters a new character. It may still be useful to record cancellation metrics separately, but it should not pollute error reporting.

Give every remote operation a deadline

A request that waits forever is usually worse than a request that fails clearly. A timeout prevents stale operations from holding resources indefinitely and gives the caller a definite point at which to choose a fallback.

Modern environments provide AbortSignal.timeout(), which creates a signal that aborts after a specified duration. MDN documents it as widely available in browsers since April 2024 and notes that a timeout produces a TimeoutError exception. Check your supported browser and runtime range before relying on it without a fallback.

async function fetchJson(url, options = {}) {
  const timeoutSignal = AbortSignal.timeout(5000);
  const signal = options.signal
    ? AbortSignal.any([options.signal, timeoutSignal])
    : timeoutSignal;

  const response = await fetch(url, {
    ...options,
    signal
  });

  if (!response.ok) {
    throw new Error(`HTTP ${response.status} from ${url}`);
  }

  return response.json();
}

There is an important detail here: combining signals means that the final error may not always tell you which signal fired. If your interface must distinguish a user cancellation from a timeout, keep the controllers separate and inspect their state after the operation rejects.

async function fetchWithDeadline(url, {
  signal: callerSignal,
  timeoutMs = 5000
} = {}) {
  const timeoutController = new AbortController();
  const timer = setTimeout(
    () => timeoutController.abort(),
    timeoutMs
  );

  const combinedSignal = callerSignal
    ? AbortSignal.any([callerSignal, timeoutController.signal])
    : timeoutController.signal;

  try {
    const response = await fetch(url, { signal: combinedSignal });

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

    return await response.json();
  } finally {
    clearTimeout(timer);
  }
}

This manual version is useful when you need a clear distinction between cancellation and timeout, or when supporting an environment without AbortSignal.timeout(). Always clear the timer in a finally block. Otherwise, completed requests can leave unnecessary timers behind.

Check HTTP failures explicitly

fetch() rejects for network-level failures, such as a broken connection or a blocked request. It does not reject merely because the server returned a 404 or 500 response. Your application must check response.ok or inspect the status code.

async function getJson(url, signal) {
  let response;

  try {
    response = await fetch(url, { signal });
  } catch (error) {
    if (error.name === 'AbortError') {
      throw error;
    }

    throw new Error(`Network failure while requesting ${url}`, {
      cause: error
    });
  }

  if (response.status === 404) {
    return null;
  }

  if (!response.ok) {
    throw new Error(`Remote service returned ${response.status}`);
  }

  return response.json();
}

The distinction matters when deciding whether to retry. A temporary network error or HTTP 503 may be retryable. A 400 caused by invalid input usually is not. A 401 may require authentication rather than another identical request. A 404 may be an expected absence rather than an exceptional failure.

Retry only when the operation is safe

Retries can improve resilience, but an automatic retry is another attempt to perform an operation. Retrying a read is generally easier to reason about than retrying a payment, order creation or other non-idempotent action.

Use exponential backoff and add jitter so that many clients do not retry at exactly the same time:

function delay(ms, signal) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) {
      reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
      return;
    }

    const timer = setTimeout(resolve, ms);

    signal?.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
    }, { once: true });
  });
}

function isRetryable(error) {
  return error?.retryable === true;
}

async function retry(operation, {
  attempts = 3,
  baseDelayMs = 250,
  signal
} = {}) {
  let lastError;

  for (let attempt = 0; attempt  attempts; attempt += 1) {
    try {
      return await operation(signal);
    } catch (error) {
      lastError = error;

      if (error.name === 'AbortError' || !isRetryable(error)) {
        throw error;
      }

      if (attempt === attempts - 1) {
        break;
      }

      const exponentialDelay = baseDelayMs * (2 ** attempt);
      const jitter = Math.random() * 100;

      await delay(exponentialDelay + jitter, signal);
    }
  }

  throw lastError;
}

This example deliberately requires the operation to identify retryable failures. Do not retry every thrown exception. Also consider the total deadline: three attempts with a five-second timeout each can turn a nominally quick request into a fifteen-second wait. A better design often gives the entire workflow one deadline and allocates the remaining time across attempts.

Do not confuse parallelism with unlimited concurrency

Starting a group of independent requests together can reduce total waiting time:

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

That is appropriate for a small, fixed set of independent operations. It is dangerous when applied to thousands of items. This pattern creates one promise per item and starts all the requests immediately:

const records = await Promise.all(
  ids.map(id => getJson(`/api/records/${id}`, signal))
);

Large batches can overwhelm the browser connection pool, your own server, a third-party API or the user’s device. They can also create a large in-memory result array and trigger rate limiting.

A small concurrency limiter can be implemented without a dependency:

async function mapWithConcurrency(items, worker, {
  concurrency = 4,
  signal
} = {}) {
  const results = new Array(items.length);
  let nextIndex = 0;

  async function run() {
    while (true) {
      if (signal?.aborted) {
        throw signal.reason ?? new DOMException('Aborted', 'AbortError');
      }

      const index = nextIndex++;

      if (index >= items.length) {
        return;
      }

      results[index] = await worker(items[index], index, signal);
    }
  }

  const workers = Array.from(
    { length: Math.min(concurrency, items.length) },
    () => run()
  );

  await Promise.all(workers);
  return results;
}

Results remain in input order even though individual tasks may finish at different times. The concurrency value should be chosen from the workload, not copied blindly. A CPU-heavy browser task may need a low value to keep the interface responsive. A network operation may tolerate more, but server limits and payload sizes still matter.

For production projects, a maintained queue library can provide features such as queue inspection and clearing. For example, p-limit exposes active and pending counts, configurable concurrency and a method for discarding queued work. Treat such libraries as implementation choices, not a substitute for understanding the workload.

Choose the right promise combinator

The promise combinator should express the business rule:

  • Promise.all() is suitable when every result is required. It rejects as soon as one input rejects, although the other operations continue running.
  • Promise.allSettled() waits for every operation and reports whether each one fulfilled or rejected. It is useful for independent work where partial success is acceptable.
  • Promise.any() resolves when the first input fulfils and rejects only if all inputs reject. It can suit fallback endpoints or alternative data sources.
  • Promise.race() settles with the first input to settle, but it does not cancel the slower operations. Use a signal if those operations should stop.

For example, an import screen may want to show successful and failed rows rather than abandon the complete batch after the first error:

const outcomes = await mapWithConcurrency(
  records,
  record => importRecord(record, signal),
  { concurrency: 4, signal }
).then(values => values.map(value => ({
  status: 'fulfilled',
  value
}))).catch(error => {
  throw error;
});

That simplified example is not enough if individual records may fail, because one rejection still stops the worker pool. Wrap each item when partial results are the requirement:

const outcomes = await mapWithConcurrency(
  records,
  async (record, index, signal) => {
    try {
      const value = await importRecord(record, signal);
      return { index, status: 'fulfilled', value };
    } catch (reason) {
      if (reason.name === 'AbortError') {
        throw reason;
      }

      return { index, status: 'rejected', reason };
    }
  },
  { concurrency: 4, signal }
);

const succeeded = outcomes.filter(item => item.status === 'fulfilled');
const failed = outcomes.filter(item => item.status === 'rejected');

Cancellation remains different from a record-level failure. If the user cancels the import, stop the whole operation rather than presenting every remaining row as an ordinary validation error.

Prevent stale results from changing current state

Cancellation is valuable, but it should not be your only defence against stale results. Some APIs or custom async functions may not support signals, and a response may already be ready when cancellation occurs.

Use a sequence number to ensure that only the latest request can update the interface:

let searchSequence = 0;
let activeController;

async function search(query) {
  const sequence = ++searchSequence;

  activeController?.abort();
  activeController = new AbortController();

  try {
    const results = await getJson(
      `/api/search?q=${encodeURIComponent(query)}`,
      activeController.signal
    );

    if (sequence !== searchSequence) {
      return;
    }

    renderResults(results);
  } catch (error) {
    if (error.name === 'AbortError') {
      return;
    }

    if (sequence === searchSequence) {
      renderSearchError(error);
    }
  }
}

This pattern protects against out-of-order responses. It is especially useful for search suggestions, filters, route changes and any interface where a new action supersedes an older one.

Clean up listeners, queues and UI state

Async reliability also includes cleanup. Event listeners should normally be registered with { once: true } when they have a single purpose. Timers need clearing. Queued work should be discarded when a component or request scope is destroyed. Loading indicators should be reset in finally, not only on success.

async function refreshPanel(signal) {
  setPanelLoading(true);

  try {
    const data = await getJson('/api/panel', signal);
    renderPanel(data);
  } catch (error) {
    if (error.name !== 'AbortError') {
      renderPanelError(error);
    }
  } finally {
    setPanelLoading(false);
  }
}

In a component framework, create the controller when the component becomes responsible for the work and abort it during unmount or disposal. In a Node.js process, connect the operation to the request or job lifecycle rather than allowing it to continue after the client has disconnected.

Security and performance considerations

Timeouts and concurrency limits are reliability controls, not security boundaries. Validate user input before constructing URLs, avoid inserting remote response content with innerHTML unless it has been safely sanitised, and keep authentication tokens out of URLs because URLs can appear in logs and browser history.

Use HTTPS for remote requests and configure the server’s CORS policy deliberately. A client-side timeout does not prevent the server from continuing work after the client has gone away. If expensive server-side jobs matter, give them their own cancellation, expiry or idempotency strategy.

Measure the behaviour you are trying to improve. Useful metrics include request duration, timeout rate, cancellation rate, retry count, queue depth, active operations and the proportion of partial failures. Avoid logging full response bodies or personal data merely to diagnose a timing problem.

Finally, do not assume that “more parallel” means “faster”. Test with realistic payload sizes, device capabilities, server limits and failure conditions. A smaller, bounded queue often produces a better user experience than a burst of hundreds of requests followed by throttling and retries.

A practical checklist

  1. Pass an AbortSignal into every cancellable async operation.
  2. Set a deadline for network work and clear manual timers in finally.
  3. Check response.ok because HTTP error statuses do not automatically reject fetch().
  4. Retry only failures that are temporary and operations that are safe to repeat.
  5. Use bounded concurrency for dynamic or large collections.
  6. Choose all, allSettled, any or race according to the required business behaviour.
  7. Protect UI state from stale responses with cancellation and, where necessary, a request sequence.
  8. Keep cancellation separate from genuine application failures in both the interface and telemetry.
  9. Clean up timers, event listeners, queues and loading state.
  10. Test slow responses, timeouts, duplicate actions, partial failure, cancellation and rate limiting.

Robust asynchronous JavaScript is mostly disciplined resource management. Once every operation has an owner, a deadline, a cancellation path and a clear failure policy, async and await become more than convenient syntax: they become the readable surface of a workflow that behaves predictably under pressure.