fix: resolve stale deriveds with latest value (#18167)

While looking into #18162 I found an adjacent bug. Currently, if an
async derived resolves in batch 2 before it resolves in batch 1, we
reject the promise belonging to batch 1 and by extension the batch
itself. This means that any other changes in batch 1 are silently
discarded, incorrectly.

The fix is almost comically simple: rather than rejecting the earlier
promise, we just resolve it with the latest value.

I have a hunch that this might also enable us to simplify the rebase
logic, though I haven't investigated that in this PR.

### Before submitting the PR, please make sure you do the following

- [x] It's really useful if your PR references an issue where it is
discussed ahead of time. In many cases, features are absent for a
reason. For large changes, please create an RFC:
https://github.com/sveltejs/rfcs
- [x] Prefix your PR title with `feat:`, `fix:`, `chore:`, or `docs:`.
- [x] This message body should clearly illustrate what problems it
solves.
- [x] Ideally, include a test that fails without this PR but passes with
it.
- [x] If this PR changes code within `packages/svelte/src`, add a
changeset (`npx changeset`).

### Tests and linting

- [x] Run the tests with `pnpm test` and lint the project with `pnpm
lint`
pull/18172/head
Rich Harris 4 months ago committed by GitHub
parent e65025be58
commit dc5bd887b5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: resolve stale deriveds with latest value

@ -232,7 +232,7 @@ export function async_derived(fn, label, location) {
for (const [b, d] of deferreds) {
deferreds.delete(b);
if (b === batch) break;
d.reject(STALE_REACTION);
d.resolve(value);
}
if (DEV && location !== undefined) {

@ -0,0 +1,29 @@
import { tick } from 'svelte';
import { test } from '../../test';
export default test({
async test({ assert, target }) {
await tick();
const [increment, pop] = target.querySelectorAll('button');
increment.click();
await tick();
increment.click();
await tick();
assert.htmlEqual(
target.innerHTML,
`<button>increment</button><button>pop</button><p>0 0 0</p>`
);
pop.click();
await tick();
assert.htmlEqual(
target.innerHTML,
`<button>increment</button><button>pop</button><p>2 2 1</p>`
);
}
});

@ -0,0 +1,22 @@
<script>
let count = $state(0);
let other = $state(0);
const queue = [];
function push(v) {
if (v === 0) return v;
return new Promise((fulfil) => {
queue.push(() => fulfil(v));
});
}
</script>
<button onclick={() => {
if (count === 0) other++;
count++;
}}>increment</button>
<button onclick={() => queue.pop()?.()}>pop</button>
<p>{await push(count)} {count} {other}</p>
Loading…
Cancel
Save