What are async methods in JavaScript?

JavascriptWeb DevelopmentFront End Technology

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>
raja
Published on 24-Jan-2018 07:37:57
Advertisements