Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

很多Web应用都需要跟异步数据打交道, 贴心的Svelte也让 await (等待)promises的值变的简单了呢. 可以直接在标签中使用await代码块:

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,所以小主不用担心条件竞争.

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}

简洁多了

Edit this page on GitHub

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>