docs: fix await_waterfall workaround — use eager const, not lazy $derived

The documentation suggested using `$derived(one())` to start promises
before awaiting them. This does not eliminate the waterfall: `$derived`
is lazy, so `one()` is still only called when `aPromise` is first read,
which happens on the `$derived(await aPromise)` line — i.e. sequentially,
after the first await completes.

Fix: replace `$derived(one())` with `const aPromise = one()` so both
functions are called eagerly before either await. Also add a NOTE that
this only helps when the promise-creating functions do not themselves
read reactive state, and that in the reactive case there is currently
no workaround.

Closes #16483
pull/18743/head
okxint 2 weeks ago
parent 7bc0a70fe6
commit 890d7f8b98

@ -93,19 +93,21 @@ let b = $derived(await two());
(Note that if the values of `await one()` and `await two()` subsequently change, they can do so concurrently — the waterfall only occurs when the deriveds are first created.) (Note that if the values of `await one()` and `await two()` subsequently change, they can do so concurrently — the waterfall only occurs when the deriveds are first created.)
You can solve this by creating the promises first and _then_ awaiting them: You can solve this by starting the promises _before_ awaiting them. Because `$derived` is lazy — the expression only runs when the value is first read — using `$derived(one())` does not help: `one()` still isn't called until `aPromise` is read for the first time, which happens on the `$derived(await aPromise)` line. Use plain `const` or `let` declarations so both functions are called eagerly, before either await runs:
```js ```js
async function one() { return 1 } async function one() { return 1 }
async function two() { return 2 } async function two() { return 2 }
// ---cut--- // ---cut---
let aPromise = $derived(one()); const aPromise = one();
let bPromise = $derived(two()); const bPromise = two();
let a = $derived(await aPromise); let a = $derived(await aPromise);
let b = $derived(await bPromise); let b = $derived(await bPromise);
``` ```
> [!NOTE] This approach only eliminates the waterfall when `one()` and `two()` do not themselves depend on reactive state. If the promise-creating expressions read `$state` or `$derived` values, there is currently no way to avoid the waterfall.
## binding_property_non_reactive ## binding_property_non_reactive
> `%binding%` is binding to a non-reactive property > `%binding%` is binding to a non-reactive property

Loading…
Cancel
Save