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 −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .result {
      font-size: 18px;
      color: blueviolet;
      font-weight: 500;
<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>
   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", () => {


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

Updated on 16-Jul-2020 13:08:14