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
manual loading/error/data เทียบกับ {#await}
หัวข้อที่มีชื่อว่า “manual loading/error/data เทียบกับ {#await}”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> );}<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 ให้เอง
ลองเล่น: simulated Promise + Reload button
หัวข้อที่มีชื่อว่า “ลองเล่น: simulated Promise + Reload button”กด Reload หลายๆ ครั้งเพื่อดูทั้งสถานะ loading และ error (มี 30% โอกาสเกิด error แบบสุ่ม) เมื่อ promise เปลี่ยน บล็อก {#await} จะ reset และเริ่มต้นใหม่อัตโนมัติ