Skip to content
Grok

Async/Await

รูปแบบการเขียนโค้ดแบบ asynchronous ที่อ่านง่าย โดยใช้ async/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));