A user clicks file A, then file B. The title says B, but the editor shows A’s contents. Both reads returned the right data. The trouble is that A’s result arrived after the user had already moved on, and nothing stopped it from being shown.

A call chain (click, load, render) can’t explain this bug, because both clicks go through exactly the same functions. You need to know when each request started and finished, and which one is allowed to update the screen. This post works through a small JavaScript example, including the error and loading states that a quick fix tends to miss.

Read up to the first await

Here’s a simplified file reader. load returns a promise for the file’s text, and publish merges a patch into the visible state. Both are passed in, so the example doesn’t depend on any UI framework:

export function createUnsafeReader(load, publish) {
  return async function select(file) {
    publish({ file, text: '', error: null, loading: true });
    try {
      const text = await load(file);
      publish({ text });
    } catch (error) {
      publish({ error: error.message });
    } finally {
      publish({ loading: false });
    }
  };
}

Before the await, the function records the selection and clears the old text. While it waits, another select call can start. After the await, nothing checks whether this request is still the one on screen.

The local variable file doesn’t change while the function is suspended, but the shared view does. That’s the whole bug: the function still has the right data for its own call, but its call is no longer the one that should be displayed.

Draw the timeline

Use two reads you can control, and let B finish before A:

Step Event Selected file Visible text Loading
1 Select A; A read starts A empty yes
2 Select B; B read starts B empty yes
3 B succeeds B B text no
4 A succeeds B A text no

Both calls ran the same code. Because of the order, the last read to finish won, when it should have been the last file selected.

Before you pick a fix, check what the UI is supposed to do. A single preview pane should show the latest selection. A batch import needs every result, and a save queue may need writes to finish in order; dropping old results would be wrong for both. The fix below is for a view where a new selection replaces the old one.

Reproduce it without timers

A test that waits 100 ms for A and 10 ms for B is slow and depends on scheduling. A deferred promise lets the test decide exactly when each read settles:

function deferred() {
  let resolve, reject;
  const promise = new Promise((yes, no) => {
    resolve = yes;
    reject = no;
  });
  return { promise, resolve, reject };
}

Create two deferred reads, select both files, resolve B, then resolve A:

const a = deferred(),
  b = deferred();
const state = {};
const select = createUnsafeReader(
  (file) => (file === 'A' ? a : b).promise,
  (patch) => Object.assign(state, patch),
);
const first = select('A'),
  second = select('B');
b.resolve('B text');
await second;
a.resolve('A text');
await first;
assert.equal(state.file, 'B');
assert.equal(state.text, 'A text'); // Reproduces the defect.

The last assertion checks for the broken result on purpose: it shows the bug really happens in this example. The test for the fixed reader expects B’s text instead. Keeping the reproduction and the fix in separate tests means nobody mistakes a green reproduction for proof that the old code works.

Give each selection a number

For a single view, a counter is enough. Increment it when a selection starts, keep the value in that call, and compare before publishing anything:

export function createReader(load, publish) {
  let latest = 0;
  return async function select(file) {
    const request = ++latest;
    publish({ file, text: '', error: null, loading: true });
    try {
      const text = await load(file);
      if (request === latest) publish({ text });
    } catch (error) {
      if (request === latest) publish({ error: error.message });
    } finally {
      if (request === latest) publish({ loading: false });
    }
  };
}

The counter belongs to this reader instance. Make it global and a click in one window would throw away results in another. Create it inside select and it resets on every call, so it can’t tell requests apart.

Comparing file paths isn’t enough either. If the user picks A, then B, then A again, the first and third requests have the same path, but the first may hold an older version of the file. The request number tells them apart.

The example assumes publish updates state synchronously and load rejects with an Error. If your framework batches updates or unmounts components, or your API rejects with something else, you’ll need to handle that too.

Test A → B → A with three separate reads

Give every invocation its own deferred promise. The earlier fixture routes A to one promise and B to another; reusing it for a second A would hide the distinction between the first and third requests.

Assume load can return different snapshots for the same path: a file might be edited between reads, for example. Here the test supplies “A version 1” and “A version 2” explicitly. These are controlled teaching examples, not a report of a Yenpo production incident. If your loader always returns the same immutable snapshot, you won’t see different text in this scenario; check its actual caching and read behavior before applying that explanation.

The download includes a deliberately incomplete createPathOnlyReader. It tracks selectedFile and guards success, error, and finally with file === selectedFile. All three checks still accept the first A once A is selected again:

Event Path-only guard Request-number guard
Select A, B, then A again Current path is A Current request is 3
Third request returns A version 2 Shows A version 2 Shows A version 2
B returns Ignores B Ignores request 2
First request returns A version 1 Shows A version 1 Keeps A version 2

The paired tests run this exact order against both readers. The reproduce: test expects the wrong version to prove the path-only guard fails; the request-number test expects version 2. Two more tests settle the first A while the third is still pending: an old success must leave the text empty and loading on, and an old failure must leave the error empty. The current A’s own failure must still appear.

Keep two readers independent

Create a reader for each independent view, with its own latest closure and its own publish target. Reuse that reader for subsequent selections in the same view; recreating it on every click loses the shared counter that invalidates older calls.

The final test creates left and right readers with separate deferred loaders and state objects, then runs this sequence:

  1. Select A on the left, A on the right, then B on the left. Left’s current number is 2; right’s is still 1.
  2. Resolve right A while left B is pending. Right must show its result and stop loading; left must stay empty and loading.
  3. Reject left’s old A. Left must keep waiting for B without an error.
  4. Resolve left B. Left must show B, and right must still show its own A.

Moving latest to module scope makes step 2 fail: left’s newer selection would invalidate right’s request and leave right loading. Sharing the visible state object would also break isolation even with separate counters. The test checks both views after the interleaved completions.

Errors and loading state can land in the wrong place too

If you only guard publish({ text }), the wrong text goes away, but two other bugs stay:

  • A fails after B is selected. A’s catch shows “A failed” on B’s view.
  • A finishes while B is still loading. A’s finally turns off B’s loading indicator.

To catch the second one, settle A while B is still pending and check right away that loading is still true. If you only look at the state after B completes, you’ll never see the indicator switch off early.

For the first one, reject A while B is pending and check that B shows no error and is still loading. Then resolve B. Add a separate test where the current request fails, too: a guard that swallows every error would pass the stale-error test while hiding real failures.

So the rule is stricter than “the right text shows up eventually”: only the current request may publish anything when it finishes, whether that’s text, an error, or turning off the spinner.

Cancelling isn’t the same as ignoring

If your loader supports cancellation, cancelling A saves work. But A can still publish after you cancel it: the result may already be cached, the operation may ignore the signal, or it may finish at the same moment you cancel.

Use cancellation to stop work you no longer need. Use the request number to decide whether a result may touch the view. And check whether your loader actually honors an AbortSignal; not every promise-returning API does.

Ignoring an old result also doesn’t undo anything load did along the way. The example loader only returns text. If a real one also writes to a shared cache or updates a model, trace those writes separately. The counter protects the view and nothing else.

Run the tests

Download async-selection.mjs and run it with Node.js 22 or later:

node --test async-selection.mjs

The ten tests cover the original A → B overwrite, success/error/loading guards, repeated A → B → A requests, and two independent readers. The two reproduce: tests deliberately assert the broken results; the other eight check the intended behavior. No timers, no dependencies.

To apply this to a real codebase, find the entry handler, every await or callback, the shared state that can change while it waits, and every write on the way back. Write down the order of events next to those source locations.

In Yenpo, you can keep the entry file open and ask the AI Reader to trace state across an await. Check its answer against the success, error, and finally paths. If it stops at “the promise resolves,” ask the follow-up: which request is allowed to use the result?