Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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: 2020-06-15T13:18:08+05:30

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements