ฟังก์ชันแบบอะซิงโครนัสถูกกำหนดด้วยคีย์เวิร์ด async และถูกนำมาใช้ใน ES 2015 ฟังก์ชันเหล่านี้ได้รับการแนะนำเพื่อกำหนดวิธีที่ดีกว่าในการเขียนสัญญาที่รัดกุมกว่าการโทรกลับ คีย์เวิร์ด await ถูกใช้ในฟังก์ชัน async เพื่อหยุดโฟลว์ของการควบคุมชั่วคราวและรอสัญญา
ต่อไปนี้เป็นรหัสสำหรับฟังก์ชันแบบอะซิงโครนัสใน JavaScript -
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
color: blueviolet;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Asynchronous functions in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to call the function asyncFunc</h3>
<script>
let BtnEle = document.querySelector(".Btn");
let resEle = document.querySelector(".result");
function displayText() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Hello World");
}, 1500);
});
}
async function asyncFunc() {
resEle.innerHTML = await displayText();
}
BtnEle.addEventListener("click", () => {
asyncFunc();
});
</script>
</body>
</html> ผลลัพธ์

เมื่อคลิกปุ่ม 'คลิกที่นี่' และรอ 2 วินาที -
