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

รันฟังก์ชันซ้ำๆ ด้วย async/await ใน JavaScript

ใช้ async/await ในลูป while เพื่อรอให้ฟังก์ชันแต่ละรอบทำงานเสร็จก่อนรอบถัดไป

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

async function test(i) {
    while (i <= 10) {
        await demo(" Call Demo1()");
        await demo(" Call Demo2()");
        i++;
    }
}

async function demo(value) {
    console.log(value);
}

test(1);

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo73.js)

ผลลัพธ์

แสดง "Call Demo1()" และ "Call Demo2()" สลับกัน 10 รอบ