Svelte基础
Svelte高阶
上下文API
特殊元素
接下来
SvelteKit基础
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
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}
简洁多了
previous next
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>