Home > Web Front-end > JS Tutorial > How to use await outside of an async function in JavaScript?

How to use await outside of an async function in JavaScript?

WBOY
Release: 2023-08-26 16:53:02
forward
1157 people have browsed it

How to use await outside of an async function in JavaScript?

In JavaScript, the async-await keyword is used to make a function asynchronous. If we make any function async, it works like multi-threads and executes the code in parallel, which helps us improve application performance.

Here, we will learn to use the await keyword outside of an asynchronous function.

Call function immediately

We will use the expression in this method to call the function immediately. We can use await keyword with promise or any other function inside the function.

grammar

Users can use function expressions to call functions immediately according to the following syntax.

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

In the above syntax, we have not created a function, but inside the curly brackets, we have written the arrow function syntax using async and await keywords.

Example 1

In the example below, we call the function immediately after defining it. Inside the expression, we define the arrow function. In the code block of the arrow function, we have used the await keyword and axios to get data from the API.

We added a CDN to use axios in the section. In the output, the user can observe the data we got from the 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>
Copy after login

Use promises

We can use Promise instead of an asynchronous function to wait until we receive a response from the server or pause the execution of the code.

grammar

Users can use Promise in JavaScript according to the following syntax.

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

In the above syntax, we use then() and catch() blocks and Promise to handle responses and errors.

Example 2

In the following example, we do the same thing as Example 1. In Example 1, we use async-await syntax and axios to get the data. Here, we use axios’ Promise to get the data. The axios.get() method returns a Promise, which we resolve using then() and catch() blocks.

<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>
Copy after login

Example 3

In this example, we create a Promise using the Promise() constructor with the new keyword. We are rejecting this commitment.

After that, we use then() and catch() blocks and the SamplePromise Promise variable to get the response or error from the Promise. The user can observe that control goes to the catch() block in the output because we reject the error.

<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>
Copy after login

This tutorial teaches users to use the await keyword outside of asynchronous functions. Additionally, we explained an alternative to using Promise to use the async-await keyword.

The above is the detailed content of How to use await outside of an async function in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template