ตัวอย่างโค้ดนี้สาธิตการใช้ async/await เพื่อให้การทำงานของฟังก์ชันใน JavaScript ดำเนินไปตามลำดับทีละขั้นตอน
โดยเริ่มจากการรอเวลา (setTimeout) จากนั้นเรียกใช้งานฟังก์ชันที่จำลองการดึงข้อมูลแบบ Promise และแสดงผลลัพธ์ออกมาในลำดับที่ถูกต้อง ทำให้โค้ดอ่านง่ายและเข้าใจได้เหมือนการทำงานแบบ synchronous แต่ยังคงใช้ประโยชน์จาก asynchronous ได้เต็มที่
ตัวอย่างโค้ดasync function sequentialExecution() {
console.log("Step 1: Start");
// await pauses the function until the Promise in step 2 is done
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("Step 2: Waited 1 second");
// You can also await functions that return a Promise
const data = await fetchDataFunction();
console.log("Step 3: Received data:", data);
console.log("Step 4: Finish");
}
function fetchDataFunction() {
return new Promise(resolve => {
// Simulate an API call
setTimeout(() => resolve("Some data"), 500);
});
}
// Call the async function to run the sequence
sequentialExecution();