Async Programming
Async Programming
Section titled “Async Programming”JavaScript เป็น single-threaded แต่ใช้ event loop จัดการ async operations ได้อย่างมีประสิทธิภาพ
ทำไมต้อง Async?
Section titled “ทำไมต้อง Async?”// ❌ ถ้าทุกอย่างเป็น sync — browser จะ freezeconst data = fetchFromAPI(); // block 2 วินาที...console.log(data); // รอจนกว่าจะเสร็จ// user คลิกอะไรไม่ได้ 2 วินาที!
// ✅ async — ไม่ blockfetchFromAPI().then(data => { console.log(data); // ทำเมื่อพร้อม});// user ใช้งานต่อได้ทันทีCallbacks (แบบเก่า)
Section titled “Callbacks (แบบเก่า)”// setTimeout ใช้ callbacksetTimeout(() => { console.log("ผ่านไป 1 วินาที");}, 1000);
// Callback Hell ❌getUser(1, (user) => { getOrders(user.id, (orders) => { getItems(orders[0].id, (items) => { console.log(items); // ซ้อนลึกมาก! }); });});import asyncio# Python ใช้ async/await เช่นเดียวกันasync def main(): data = await fetch_data()// C ใช้ threads หรือ callbacks ผ่าน function pointersvoid callback(int result) { printf("%d", result); }async_operation(callback);-- SQL โดยทั่วไปเป็น synchronous-- async ถูกจัดการที่ application layerSELECT * FROM users WHERE id = 1;Promises
Section titled “Promises”Promise มี 3 สถานะ: pending → fulfilled (สำเร็จ) หรือ rejected (ล้มเหลว)
// สร้าง Promiseconst promise = new Promise((resolve, reject) => { const success = true; if (success) { resolve("สำเร็จ!"); } else { reject(new Error("ล้มเหลว")); }});
// ใช้ .then / .catchpromise .then(result => console.log(result)) // "สำเร็จ!" .catch(error => console.error(error)) .finally(() => console.log("เสร็จสิ้น"));async/await (วิธีสมัยใหม่)
Section titled “async/await (วิธีสมัยใหม่)”// async function จะ return Promise เสมอasync function fetchUser(id) { const response = await fetch(`https://api.example.com/users/${id}`); const data = await response.json(); return data;}
// เรียกใช้const user = await fetchUser(1);console.log(user.name);fetch() API
Section titled “fetch() API”// GET requestasync function getUsers() { const res = await fetch("https://jsonplaceholder.typicode.com/users");
if (!res.ok) { throw new Error(`HTTP ${res.status}: ${res.statusText}`); }
return await res.json();}
// POST requestasync function createUser(userData) { const res = await fetch("https://jsonplaceholder.typicode.com/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(userData), });
return await res.json();}Promise.all & Promise.allSettled
Section titled “Promise.all & Promise.allSettled”// Promise.all — รอทั้งหมด (fail ถ้า 1 ตัว reject)const [users, posts] = await Promise.all([ fetch("/api/users").then(r => r.json()), fetch("/api/posts").then(r => r.json()),]);
// Promise.allSettled — รอทั้งหมด (ไม่ fail)const results = await Promise.allSettled([ fetch("/api/users").then(r => r.json()), fetch("/api/bad-url").then(r => r.json()),]);// [{ status: "fulfilled", value: [...] }, { status: "rejected", reason: Error }]