如何在 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.