การประกาศฟังก์ชัน async ตามชื่อที่แนะนำจะกำหนดฟังก์ชันแบบอะซิงโครนัส ฟังก์ชันนี้ส่งคืนอ็อบเจ็กต์ AsyncFunction
ไวยากรณ์
นี่คือไวยากรณ์ −
async function functionname([param[, param[, ... param]]]) {
statements to be executed
} ตัวอย่าง
มาดูตัวอย่างกัน ซึ่งจะพิมพ์ผลลัพธ์หลังจาก 5 วินาที −
<html>
<body>
<script>
function displayFunction(num) {
return new Promise(resolve => {
setTimeout(() => {
resolve(num);
}, 5000);
});
}
async function add2(num) {
const x = displayFunction(7);
const y = displayFunction(5);
return num * await x * await y;
}
add2(15).then(result => {
document.write("Multiplication Result (after 5 seconds): "+result);
});
</script>
</body>
</html>