รอ...ของ
'รอ...ของ ' คำสั่งจะสร้างการวนซ้ำบน async วัตถุและ ซิงค์ ออบเจ็กต์ เช่น อาร์เรย์ ออบเจ็กต์คล้ายอาร์เรย์ ชุดแผนที่ เป็นต้น
ไวยากรณ์
for await (variable of iterable) {
statement
} ตัวอย่าง
ในตัวอย่างต่อไปนี้ "รอ...ของ คำสั่ง " ใช้เพื่อวนซ้ำอาร์เรย์ปกติในรูปแบบ async และจำนวนเต็มแสดงตั้งแต่ 1 ถึง 5 ตามที่แสดงในเอาต์พุต
<html>
<body>
<script>
var txt = "";
const array = [1,2,3,4,5];
async function test() {
for await (const p of array) {
var txt = p + "</br>";
document.write(txt);
}
}
test();
</script>
</body>
</html> ผลลัพธ์
1 2 3 4 5
ในการเรียก async ทำงานวนเป็นสัญลักษณ์ใหม่ "Symbol.asyncIterator " และ "รอ...ของ ใช้ "construct" ที่สำคัญที่สุด "for-await...of " มีบทบาทสำคัญในการวนซ้ำวัตถุ async iterable
ตัวอย่าง
ในตัวอย่างต่อไปนี้โดยใช้ "for await...of " ซึ่งวนซ้ำบน async iterable แสดงจำนวนเต็มตั้งแต่ 1 ถึง 5
<html>
<body>
<script>
var txt = "";
var async = {
[Symbol.asyncIterator]() {
return {
i: 1,
next() {
if (this.i < 6) {
return Promise.resolve({ value: this.i++, done : false});
}
}
};
}
};
async function test() {
for await (let p of async) {
txt = p + "</br>"
document.write(txt);
}
}
test();
</script>
</body>
</html> ผลลัพธ์
1 2 3 4 5