如何在 JavaScript 中非同步函式外部使用 await?


在 JavaScript 中,async-await 關鍵字用於使函式非同步。如果我們將任何函式設為非同步,它就會像多執行緒一樣並行執行程式碼,這有助於我們提高應用程式效能。

在這裡,我們將學習如何在非同步函式外部使用 await 關鍵字。

立即呼叫函式

我們將使用表示式在這種方法中立即呼叫函式。我們可以在函式內部使用 await 關鍵字與 Promise 或任何其他函式一起使用。

語法

使用者可以遵循以下語法立即使用函式表示式呼叫函式。

(async () => {
   let result = await fetchData();
})();

在上面的語法中,我們沒有建立函式,而是在大括號內編寫了帶有 async 和 await 關鍵字的箭頭函式語法。

示例 1

在下面的示例中,我們在定義函式後立即呼叫它。在表示式內,我們定義了箭頭函式。在箭頭函式的程式碼塊中,我們使用了帶有 axios 的 await 關鍵字來從 API 獲取資料。

我們在 <head> 部分添加了 CDN 來使用 axios。在輸出中,使用者可以看到我們從 API 獲取的資料。

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.3/axios.min.js"> </script>
</head>
<body>
   <h2>Using the <i>await</i> with immediately invoking function expression.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');

      (async () => {
         let result = await axios.get("https://dummyjson.com/products/1");

         output.innerHTML += "The results from the API is <br/>";
         for (let key in result.data) {
            output.innerHTML += key + " : " + result.data[key] + "<br/>";
         }
      })();
   </script>
</body>
</html>

使用 Promise

我們可以使用 Promise 來替代非同步函式,等待我們從伺服器獲得響應或掛起程式碼的執行。

語法

使用者可以遵循以下語法在 JavaScript 中使用 Promise。

promise.then((response) => {
   // use response
})
.catch((err) => {
   // handle the errors
})

在上面的語法中,我們使用了 then() 和 catch() 塊與 Promise 一起處理響應和錯誤。

示例 2

在下面的示例中,我們執行的操作與示例 1 相同。在示例 1 中,我們使用了帶有 axios 的 async-await 語法來獲取資料。在這裡,我們使用了帶有 axios 的 Promise 來獲取資料。axios.get() 方法返回 Promise,我們使用 then() 和 catch() 塊來解析它。

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.3/axios.min.js"> </script>
</head>
<body>
   <h2>Using the <i>promises</i> instead of async-await.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      (() => {
         axios.get("https://dummyjson.com/products/1").then((result) => {

            output.innerHTML += "The results from the API is <br/>";
            for (let key in result.data) {
                  output.innerHTML += key + " : " + result.data[key] + "<br/>";
            }
         })
         .catch((err) => {
            output.innerHTML += "The error is " + err;
         })
      })();
   </script>
</body>
</html>

示例 3

在這個示例中,我們使用帶有 new 關鍵字的 Promise() 建構函式建立了一個 Promise。我們正在拒絕這個 Promise。

之後,我們使用 then() 和 catch() 塊與 SamplePromise Promise 變數一起獲取 Promise 的響應或錯誤。使用者可以觀察到,由於我們拒絕了錯誤,控制權轉到了 catch() 塊。

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.3/axios.min.js"> </script>
</head>
<body>
   <h2>Using the <i>promises</i> instead of async-await.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let SamplePromise = new Promise((resolve, reject) => {
         reject("Promise is rejected without any error");
      })
      SamplePromise.then((response)=>{
         output.innerHTML += "Response from the promise is " + response;
      })
      .catch((err)=>{
         output.innerHTML += "The error message is - " + err;
      })
   </script>
</body>
</html>

本教程教使用者如何在非同步函式外部使用 await 關鍵字。此外,我們還解釋了使用 Promise 來使用 async-await 關鍵字的替代方法。

更新於:2023年2月16日

1K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.