什麼是 JavaScript 中的非同步方法?


顧名思義,非同步函式宣告定義了一個非同步函式。此函式會返回 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>

更新於: 2020 年 6 月 15 日

138 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.