ข้ามไปยังเนื้อหา

Async Patterns

นักพัฒนา React จัดการ loading/error state ด้วย useState แบบ manual หรือใช้ Suspense + react-query เพื่อลด boilerplate Svelte มีทางออกแบบ declarative ในตัว: {#await promise}...{:then value}...{:catch err}...{/await} จัดการทั้งสามสถานะ — กำลังโหลด, สำเร็จ, และ error — ใน markup รวดเดียว ไม่ต้องมี flag manual ให้ track

React
function PostList() {
const [posts, setPosts] = React.useState([]);
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(null);
React.useEffect(() => {
fetch('/api/posts')
.then(r => r.json())
.then(data => { setPosts(data); setLoading(false); })
.catch(e => { setError(e.message); setLoading(false); });
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<ul>
{posts.map(p => <li key={p.id}>{p.title}</li>)}
</ul>
);
}
Svelte
<script>
const postsPromise = fetch('/api/posts').then(r => r.json());
</script>
{#await postsPromise}
<p>Loading...</p>
{:then posts}
<ul>
{#each posts as p}
<li>{p.title}</li>
{/each}
</ul>
{:catch error}
<p>Error: {error.message}</p>
{/await}

สังเกตว่าโค้ด Svelte ไม่มี state variables เลย — {#await} ติดตามสถานะของ Promise โดยตรงและ render ตาม block ที่ถูกต้องอัตโนมัติ เมื่อ Promise resolve หรือ reject Svelte จะ update UI ให้เอง

กด Reload หลายๆ ครั้งเพื่อดูทั้งสถานะ loading และ error (มี 30% โอกาสเกิด error แบบสุ่ม) เมื่อ promise เปลี่ยน บล็อก {#await} จะ reset และเริ่มต้นใหม่อัตโนมัติ

บล็อก {#await} ของ Svelte มี block กี่ส่วน?
คุณทำให้ {#await} fetch ข้อมูลใหม่อย่างไร?
{#await} ต่างจาก useEffect + loading state อย่างไร?
syntax ที่ถูกต้องสำหรับ {#await} block ที่มีทั้งสาม state คืออะไร?