Skip to content

Async/Await

เป็นรูปแบบที่ทำให้การเขียนโค้ดแบบ asynchronous อ่านง่ายขึ้น โดยใช้ keywords async และ await ช่วยให้เขียนโค้ดแบบ non-blocking ในรูปแบบที่อ่านเข้าใจง่ายคล้ายกับโค้ดแบบ synchronous ทั่วไป async ใช้ประกาศฟังก์ชันที่จะมีการใช้ await ภายใน ส่วน await ใช้รอให้ Promise ทำงานเสร็จก่อนดำเนินการต่อ

js
// Function to fetch data from an API
async function fetchData() {
  try {
    // Wait for the fetch request to complete
    const response = await fetch("https://api.example.com/data");
    // Wait for the JSON parsing to complete
    const data = await response.json();
    return data;
  } catch (error) {
    // Catch any errors that might occur
    console.error("Error occurred:", error);
  }
}

Promise

เป็น object ที่ใช้จัดการกับการทำงานแบบ asynchronous และผลลัพธ์ที่จะเกิดขึ้นในอนาคต Promise มีสถานะ 3 แบบคือ pending (กำลังทำงาน), fulfilled (สำเร็จ) และ rejected (ล้มเหลว) ช่วยให้จัดการกับการทำงานแบบ non-blocking และจัดการกับ callback hell ได้อย่างมีประสิทธิภาพ

js
// Function that returns a Promise
const fetchData = () => {
  return new Promise((resolve, reject) => {
    // Perform asynchronous operation
    fetch("https://api.example.com/data")
      .then(response => response.json())
      .then(data => resolve(data))
      .catch(error => reject(error));
  });
};

// Using the Promise
fetchData()
  .then(data => console.log(data))
  .catch(error => console.error("Error occurred:", error));