AceDevHub
Advanced JavaScript Interview QuestionsAdvancedScenario

JavaScript · Question 88

How would you prevent an older asynchronous request from overwriting a newer result in a JavaScript UI?

Direct answer

Treat the problem as ordering, not just cancellation: cancel obsolete work when possible and also guard result application with a request identity, sequence number, or current-state check so stale completions cannot commit.

Suppose search request A starts for "rea", then request B starts for "react". B may finish first. If A later resolves and blindly writes to the UI, the interface regresses to stale data even though every Promise completed successfully.

A robust pattern increments a request version and captures the version for each request. Before committing its result, the handler verifies that its version is still the current one. If the underlying API supports cancellation, an AbortController can additionally stop obsolete network work, but correctness should not rely on cancellation always winning the race.

  • Cancellation saves resources; a commit guard protects correctness.
  • State libraries often encode the same concept using request IDs, latest-only operators, or reducer checks.
  • The same race appears in autosuggest, route loading, validation, image processing, and any UI where input changes faster than asynchronous work completes.