Async function declaration ตามชื่อ แสดงถึง asynchronous function ฟังก์ชันนี้คืนค่า AsyncFunction object (ซึ่งเป็น Promise)
Syntax
async function functionName([param[, param[, ... param]]]) {
// statements to be executed
}
ตัวอย่าง
ตัวอย่างพิมพ์ผลลัพธ์หลัง 5 วินาที:
<html>
<body>
<script>
function displayFunction(num) {
return new Promise(resolve => {
setTimeout(() => {
resolve(num);
}, 5000);
});
}
async function add2(num) {
const x = displayFunction(7);
const y = displayFunction(5);
return num * await x * await y;
}
add2(15).then(result => {
document.write("Multiplication Result (after 5 seconds): " + result);
});
</script>
</body>
</html>
รายละเอียด Async/Await
asyncทำให้ฟังก์ชันคืนค่า Promise เสมอawaitหยุด (pause) ฟังก์ชันจนกว่า Promise จะ resolve — ใช้ได้เฉพาะใน async functionawaitunwrapping Promise ให้ค่า resolved value โดยตรง- Error handling: ใช้
try/catchรอบawait
ตัวอย่าง Error Handling
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch failed:', error);
throw error; // re-throw หรือ return default value
}
}
Parallel vs Sequential
// Sequential (ช้ากว่า - รอทีละอัน) const user = await fetchUser(id); const posts = await fetchPosts(id); // Parallel (เร็วกว่า - รอพร้อมกัน) const [user, posts] = await Promise.all([ fetchUser(id), fetchPosts(id) ]);