跳至主要內容

{#await ...}

{#await expression}...{:then name}...{:catch name}...{/await}
{#await expression}...{:then name}...{/await}
{#await expression then name}...{/await}
{#await expression catch name}...{/await}

Await 區塊允許您根據 Promise 的三種可能狀態進行分支 — 待定、已實現或已拒絕。

{#await promise}
	<!-- promise is pending -->
	<p>waiting for the promise to resolve...</p>
{:then value}
	<!-- promise was fulfilled or not a Promise -->
	<p>The value is {value}</p>
{:catch error}
	<!-- promise was rejected -->
	<p>Something went wrong: {error.message}</p>
{/await}

在伺服器端渲染期間,只會渲染待定分支。

如果提供的表達式不是 Promise,則只會渲染 :then 分支,包括在伺服器端渲染期間。

如果 promise 拒絕(或不可能發生錯誤),則可以省略 catch 區塊,如果您不需要渲染任何內容。

{#await promise}
	<!-- promise is pending -->
	<p>waiting for the promise to resolve...</p>
{:then value}
	<!-- promise was fulfilled -->
	<p>The value is {value}</p>
{/await}

如果您不關心待定狀態,也可以省略初始區塊。

{#await promise then value}
	<p>The value is {value}</p>
{/await}

同樣地,如果您只想顯示錯誤狀態,則可以省略 then 區塊。

{#await promise catch error}
	<p>The error is {error}</p>
{/await}

您可以使用 #awaitimport(...) 來延遲渲染元件

{#await import('./Component.svelte') then { default: Component }}
	<Component />
{/await}

在 GitHub 上編輯此頁面

上一頁 下一頁