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.