What are async methods in JavaScript?


The async function declaration as the name suggests defines an asynchronous function. This function returns an AsyncFunction object.

Syntax

Here’s the syntax −

async function functionname([param[, param[, ... param]]]) {
   statements to be executed
}

Example

Let’ see an example, which prints the result after 5 seconds −

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

Updated on: 15-Jun-2020

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements