Explain asynchronous functions in JavaScript with an example

JavascriptWeb DevelopmentObject Oriented Programming

The asynchronous functions are defined with async keyword and were introduced in ES 2015. These functions were introduced to define a better way to write consice promises than callback. The await keyword is used inside an async function to pause the flow of control and it waits for promise.

Following is the code for asynchronous functions in JavaScript −

Example

 Live Demo

<!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>

Output

On clicking the ‘CLICK HERE’ button and waiting for 2 seconds −

raja
Published on 16-Jul-2020 13:06:08
Advertisements