Skip to main content

{#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 の 3 つの可能な状態 — 待機 (pending)、成功 (fulfilled)、または失敗 (rejected) — に応じて処理を分岐させることができます。

{#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(...) と組み合わせることで、コンポーネントを遅延的 (lazily) にレンダリングすることができます:

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

Edit this page on GitHub