Skip to content

Async Programming

JavaScript เป็น single-threaded แต่ใช้ event loop จัดการ async operations ได้อย่างมีประสิทธิภาพ

// ❌ ถ้าทุกอย่างเป็น sync — browser จะ freeze
const data = fetchFromAPI(); // block 2 วินาที...
console.log(data); // รอจนกว่าจะเสร็จ
// user คลิกอะไรไม่ได้ 2 วินาที!
// ✅ async — ไม่ block
fetchFromAPI().then(data => {
console.log(data); // ทำเมื่อพร้อม
});
// user ใช้งานต่อได้ทันที
// setTimeout ใช้ callback
setTimeout(() => {
console.log("ผ่านไป 1 วินาที");
}, 1000);
// Callback Hell ❌
getUser(1, (user) => {
getOrders(user.id, (orders) => {
getItems(orders[0].id, (items) => {
console.log(items); // ซ้อนลึกมาก!
});
});
});

Promise มี 3 สถานะ: pendingfulfilled (สำเร็จ) หรือ rejected (ล้มเหลว)

// สร้าง Promise
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("สำเร็จ!");
} else {
reject(new Error("ล้มเหลว"));
}
});
// ใช้ .then / .catch
promise
.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);
// GET request
async 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 request
async 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 — รอทั้งหมด (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 }]