mirror of https://github.com/sveltejs/svelte
parent
5180d7fafa
commit
b5f74b0843
@ -0,0 +1,63 @@
|
||||
import { tick } from 'svelte';
|
||||
import { test } from '../../test';
|
||||
|
||||
export default test({
|
||||
async test({ assert, target }) {
|
||||
const [a, t, shift_a, shift_t] = target.querySelectorAll('button');
|
||||
|
||||
shift_a.click();
|
||||
shift_t.click();
|
||||
await tick();
|
||||
assert.htmlEqual(
|
||||
target.innerHTML,
|
||||
`
|
||||
<button>a</button>
|
||||
<button>t</button>
|
||||
<button>shift a</button>
|
||||
<button>shift t</button>
|
||||
<p>async a: 0</p>
|
||||
<p>late read: -1</p>
|
||||
`
|
||||
);
|
||||
|
||||
// batch A: writes `a`, stays pending (its promise is unresolved)
|
||||
a.click();
|
||||
await tick();
|
||||
|
||||
// batch B: writes `t`; resolve its promise so the continuation
|
||||
// reads `a` for the first time while A is still pending. This
|
||||
// entangles B with A — both worlds are held back and commit together
|
||||
t.click();
|
||||
await tick();
|
||||
shift_t.click();
|
||||
await tick();
|
||||
|
||||
assert.htmlEqual(
|
||||
target.innerHTML,
|
||||
`
|
||||
<button>a</button>
|
||||
<button>t</button>
|
||||
<button>shift a</button>
|
||||
<button>shift t</button>
|
||||
<p>async a: 0</p>
|
||||
<p>late read: -1</p>
|
||||
`
|
||||
);
|
||||
|
||||
// commit the merged batch
|
||||
shift_a.click();
|
||||
await tick();
|
||||
|
||||
assert.htmlEqual(
|
||||
target.innerHTML,
|
||||
`
|
||||
<button>a</button>
|
||||
<button>t</button>
|
||||
<button>shift a</button>
|
||||
<button>shift t</button>
|
||||
<p>async a: 1</p>
|
||||
<p>late read: 1</p>
|
||||
`
|
||||
);
|
||||
}
|
||||
});
|
||||
@ -0,0 +1,35 @@
|
||||
<script>
|
||||
let a = $state(0);
|
||||
let t = $state(0);
|
||||
|
||||
let deferreds = [];
|
||||
|
||||
function push(key, v) {
|
||||
const d = Promise.withResolvers();
|
||||
deferreds.push({ key, v, d });
|
||||
return d.promise;
|
||||
}
|
||||
|
||||
function shift(key) {
|
||||
const i = deferreds.findIndex((d) => d.key === key);
|
||||
if (i === -1) return;
|
||||
const [{ v, d }] = deferreds.splice(i, 1);
|
||||
d.resolve(v);
|
||||
}
|
||||
</script>
|
||||
|
||||
<button onclick={() => a++}>a</button>
|
||||
<button onclick={() => t++}>t</button>
|
||||
<button onclick={() => shift('a')}>shift a</button>
|
||||
<button onclick={() => shift('t')}>shift t</button>
|
||||
|
||||
<svelte:boundary>
|
||||
<p>async a: {await push('a', a)}</p>
|
||||
|
||||
<!-- reads `a` after an await, but only once t > 0 -->
|
||||
<p>late read: {(await push('t', t), t > 0 ? a : -1)}</p>
|
||||
|
||||
{#snippet pending()}
|
||||
<p>loading...</p>
|
||||
{/snippet}
|
||||
</svelte:boundary>
|
||||
Loading…
Reference in new issue