Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

大多数 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>