大多数 Web 应用在某些时候都必须处理异步数据。Svelte 可让你轻松地在标记中直接等待 promises 的值:
¥Most web applications have to deal with asynchronous data at some point. Svelte makes it easy to await the value of promises directly in your markup:
App
{#await promise}
<p>...rolling</p>
{:then number}
<p>you rolled a {number}!</p>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}
仅考虑最近的
promise
,这意味着你不必担心竞争条件。¥[!NOTE] Only the most recent
promise
is considered, meaning you don’t need to worry about race conditions.
如果你知道你的 promise 不能拒绝,则可以省略 catch
块。如果你不想在 promise 解决之前显示任何内容,也可以省略第一个块:
¥If you know that your promise can’t reject, you can omit the catch
block. You can also omit the first block if you don’t want to show anything until the promise resolves:
{#await promise then number}
<p>you rolled a {number}!</p>
{/await}
上一页 下一页
1
2
3
4
5
6
7
8
9
10
11
12
<script>
import { roll } from './utils.js';
let promise = $state(roll());
</script>
<button onclick={() => promise = roll()}>
roll the dice
</button>
<p>...rolling</p>