Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Asynchronous Loop ใน JavaScript: await ใน Loop กับ Promise


การวนลูปแบบ Asynchronous (รอ Promise ทีละรอบ) ทำได้ด้วย for...of + await ภายใน async function ไม่สามารถใช้ forEach กับ await ได้โดยตรง เพราะ forEach ไม่รอ Promise

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Async Loop</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: blueviolet; }
  </style>
</head>
<body>
  <h1>Asynchronous Loop ใน JavaScript</h1>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>กดปุ่มเพื่อเริ่ม Async Loop (รอ 2 วินาทีต่อรอบ)</h3>
  <script>
    const resEle = document.querySelector(".result");
    // Helper: สร้าง Promise ที่ resolve หลัง ms milliseconds
    const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
    async function asyncLoop() {
      for (let i = 0; i < 10; i++) {
        await wait(2000); // รอ 2 วินาที
        resEle.innerHTML += "i = " + i + "<br>";
      }
    }
    document.querySelector(".Btn").addEventListener("click", () => {
      asyncLoop();
    });
  </script>
</body>
</html>

ผลลัพธ์

Asynchronous Loop ใน JavaScript: await ใน Loop กับ Promise

เมื่อกดปุ่ม "คลิกที่นี่" (ลูปพิมพ์ 0-9 ทีละ 2 วินาที):

Asynchronous Loop ใน JavaScript: await ใน Loop กับ Promise

รูปแบบ Async Loop ต่างๆ

// 1. for...of + await (Sequential - ทีละอัน) ✅ แนะนำ
async function sequential(items) {
  for (const item of items) {
    await process(item); // รอจบก่อนรอบถัดไป
  }
}

// 2. for...of + Promise.all (Parallel - พร้อมกัน) ✅ เร็วกว่า
async function parallel(items) {
  await Promise.all(items.map(item => process(item)));
}

// 3. for...of + Promise.allSettled (Parallel + ไม่ fail-fast)
async function parallelSafe(items) {
  const results = await Promise.allSettled(items.map(item => process(item)));
  return results.map(r => r.status === "fulfilled" ? r.value : r.reason);
}

// 4. for...of + Batching (ควบคุม Concurrency)
async function batched(items, concurrency = 3) {
  const results = [];
  for (let i = 0; i < items.length; i += concurrency) {
    const batch = items.slice(i, i + concurrency);
    const batchResults = await Promise.all(batch.map(item => process(item)));
    results.push(...batchResults);
  }
  return results;
}

// 5. ❌ forEach + await - ไม่ทำงาน (ไม่รอ Promise)
async function broken(items) {
  items.forEach(async (item) => {
    await process(item); // รันพร้อมกัน ไม่รอ!
  });
  console.log("Done"); // พิมพ์ก่อน process จบ
}

Error Handling ใน Async Loop

async function safeLoop(items) {
  for (const item of items) {
    try {
      await process(item);
    } catch (err) {
      console.error("Failed:", item, err);
      // ตัดสินใจ: continue, break, หรือ re-throw
    }
  }
}

// หรือใช้ Promise.allSettled
async function safeLoop2(items) {
  const results = await Promise.allSettled(items.map(process));
  results.forEach((result, i) => {
    if (result.status === "rejected") {
      console.error("Item", i, "failed:", result.reason);
    }
  });
}

Top-level Await (ES2022, Modules)


// ใน ES Module (