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


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

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

Invoke the function immediately

We will use the expression in this approach to invoke the function immediately. We can use the await keyword with the promises or any other function inside the function.

Syntax

Users can follow the syntax below to use the function expression to invoke the function immediately.

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

In the above syntax, we haven’t created the function, but inside the braces, we have written the arrow function syntax with async and await keywords.

Example 1

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

We have added the CDN in the <head> section to use the axios. In the output, users can observe the data we get 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>

Use the Promises

We can use the promises instead of the asynchronous function to wait until we get a response from the server or suspend the execution of the code.

Syntax

Users can follow the syntax below to use the promises in JavaScript.

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

In the above syntax, we have used the then()and catch() block with the promise to handle the response and error.

Example 2

In the example below, we are doing the same thing as in example 1. In example 1, we used the async-await syntax with the axios to get the data. Here, we have used the promise with axios to get the data. The axios.get() method returns the promise, which we are resolving using the then() and catch() block.

<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>

Example 3

In this example, we have created a promise using the Promise() constructor with a new keyword. We are rejecting the promise.

After that, we used the then() and catch() block with the SamplePromise promise variable to get the response or error from the promise. Users can observe that control goes to the catch() block in the output as we have rejected 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>

This tutorial taught users to use the await keyword outside of an async function. Also, we have explained the alternative way to use the async-await keyword using the promises.

Updated on: 16-Feb-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements