JavaScript 中的异步方法是什么?


正如其名称所暗示的,async 函数声明定义了一个异步函数。此函数返回一个 AsyncFunction 对象。

语法

以下是语法 −

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

示例

让我们看一个在 5 秒后打印结果的示例 −

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

更新于: 15-6-2020

138 次浏览

开启你的职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.