Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to use await outside of an async function in JavaScript ?

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

In this article, we will try to understand in what way or by how we may use await outside of an async function in JavaScript with the help of both theoretical explanations as well as coding examples.

Let us first understand the following shown section in which all the syntaxes of declaring a promise, executing a promise, and using async-await keywords, are enlightened in a brief manner:

Syntax: The following shown syntax is getting in use in order to declare a promise in JavaScript:

let new_promise_variable = 
    new Promise ((resolve, reject) => {
        // either use resolve()
        // or use reject() method
    });

The following shown syntax will help us to understand how we to execute a declared promise in JavaScript:

new_promise_variable.then((data) => {
    // Either use console.log() for data
    // or use return statement
}).catch((error) => {
    // Catch the error, if caught
})

Another shown syntax will help us to understand how to use async-await keywords for declaring an async function followed by fetching the data properly using await-keyword:

async function function_name () {
    let data_to_be_retrieved = await data_function();
    // Do something with the fetched data
}

Now after analyzing all the above-shown syntaxes (shown above), let us have a look over the below-enlightened examples which will help us to understand the syntaxes properly.

Example 1: 

  • In this example, we will simply create a method and inside that method, we will return a promise which will actually use the resolve() method in order to display the data successfully. 
  • Later we will store the value (promise value to be precise) that we have received from the same method itself inside a new variable. 
  • Further, we will use the then() method in order to display our value as outside, and also we will attach a catch() method which will the error if caught so at any stage of data execution. 

Javascript




<script>
    let getData = () => {
        return new Promise((resolve, reject) => {
            resolve("This article is available "
                + "on neveropen...");
        });
    };
  
    let data = getData();
    data
        .then((result) => {
            console.log(result);
        })
        .catch((error) => {
            console.log(error);
        });
</script>


Output:

This article is available on neveropen...

Example 2: 

  • In this example, we will declare the same method as declared previously that actually contains a promise but here we will execute it in a slightly changed manner. 
  • Here we will declare another method, using async-keyword, which marks this method to handle all the asynchronous data operations successfully. 
  • After this, we will declare a try-catch block inside this method and inside the try-block, we will declare a variable inside which we will fetch our data contained in a method using the await-keyword itself. 
  • Later using the console.log() method we will display the result as output and further will attach a catch() method that will help us to catch any caught error at any stage itself.

Javascript




<script>
    let getData = () => {
        return new Promise((resolve, reject) => {
            resolve("This article is available"
                + " on neveropen...");
        });
    };
  
    let fetchData = async () => {
        try {
            let data = await getData();
            console.log(data);
        } catch (error) {
            console.log(error);
        }
    };
  
    fetchData();
</script>


Output:

This article is available on neveropen...

Now that we have understood things completely in a very deep and detailed manner, let us now look over the below-enlightened example which will help us to understand our main task which is how we could use await outside of the async-function. 

Example 3: 

  • First, the important thing to note down here is that there is no direct way possible to use await outside of the async-function, but for our convenience, we will try to do it with the help of IIFE (Immediately Invoked Function Expression).
  • Here in this example, we will create a method again that will actually return a new promise variable and this time to understand things better instead of resolve() method we will use reject() method itself. 
  • Then for promise data execution, we will declare an IIFE, which is though async in nature and then we will use a try-catch block during execution,
  • Inside try-block we will declare a variable that will actually fetch our data with the help of the await-keyword itself and after this, we will attach a catch() method that will catch our error which we have passed inside the reject() method of promise.

Javascript




<script>
    let getData = () => {
        return new Promise((resolve, reject) => {
            reject("Something went wrong!!...");
        });
    };
  
    (async () => {
        try {
            let data = await getData();
            console.log(data);
        } catch (error) {
            console.log(error);
        }
    })();
</script>


Output:

Something went wrong!!...

RELATED ARTICLES

Most Popular

Recent Comments