Async/Await Functions in JavaScript



Handling asynchronous tasks is essential for network programming. In JavaScript most cases, we ask for data that are not synchronous to our system. To handle asynchronous systems, we can use Async and Await functions in JavaScript. The async keyword which is used with a function will qualify a javascript function as an asynchronous function.

Async Function

The async functions are very similar to the normal functions in javascript. The syntax is like below− From the syntax, it is clear that only the ‘async’ keyword is added to the function signature.

Syntax

async function name(param1, param2, ...paramN) {
   // function body
}

Example

Let us see one simple example of the async function in javascript.

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { async function myAsyncFunction() { content += "From Async function body" return Promise.resolve(1); } myAsyncFunction(); } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

From this example output, we cannot see any difference from than normal function output. But when the async keyword is used it returns a promise object. With this promise, we can apply the method-chaining to use the then() function. The following example is showing it.

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { async function myAsyncFunction() { content += "From Async function body" + '<br>' return Promise.resolve(1000); } myAsyncFunction().then(function (result) { content += result + "<br>" opDiv.innerHTML = content }); } catch (err) { error += err } finally { // display on output console .innerHTML = error } </script> </body> </html>

This example is similar to the previous one, but it uses the then() function to check whether the function got resolved or not, if so then return the output directly from it.

Await Keyword

We cannot see any special action for the async function in the last example, this is because to see the effect of async, we need to set up the environment for asynchronous systems. We can do this by incorporating additional delays. In real examples file access or downloading larger files from the web will take a longer time which will be asynchronous, in that case, the async function will become handy.

To process the promise after a certain duration, we need to specify that it must wait for a while. So that the await keyword is used. Let us see the syntax and some basic examples.

Syntax

let object = await <some promise>;

Example

Let us see one simple example of await keyword.

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { // Creating a promise let myPromise = new Promise(function (resolve, reject) { setTimeout(function () { resolve('Promise resolved') }, 4000); // resolve after 4 seconds }); // define one async function async function myAsyncFunction() { content += "Wait for some time..." + '<br>' opDiv.innerHTML = content // wait until the promise resolves let result = await myPromise; content += result + '<br>' content += 'The promise has been resolved' + '<br>' opDiv.innerHTML = content } myAsyncFunction(); } catch (err) { error += err } finally { // display on output console opErrDiv.innerHTML = error } </script> </body> </html>

Directly seeing this output will not make much sense. If you execute this code on your own, you can see the first line “Wait for some time...” is printed first, then it is waiting for 4 seconds (4000 milliseconds) to generate the next output. This is because we have created one promise which resolves after 4 seconds and returns the ‘Promise Resolved’ string.

Error Handling from Async function

Raising an error is a common thing from async functions. For example, if we are trying to download some object from the web, it starts downloading by a promise object. But after some time, there is a network failure or permission issue or any other issue occurred, so this will not complete its tasks successfully and raise an error. This error can be handled directly by using catch() or basic try-catch blocks.

Syntax

asyncFunc().catch(
   // handle error coming from async function
)

Example

Let us see one example of catching errors while using the promise and async functions.

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { // Creating a promise function fetchUser(id) { if (typeof id !== 'number' || id <= 0) { throw new Error('ID is invalid, check again'); } return new Promise((resolve, reject) => { resolve({ id: id, username: 'someUser' }); }); } fetchUser('id1') .then(user => content += JSON.stringify(user.username)) .catch(err => error += err); } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

In the above example, we have caught an error using the .catch() method chain. This will check the error directly from the promise. We can also catch and handle errors from outside. This can be done using the exception handling method (try-catch) statements in javascript.

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { // Creating a promise function fetchUser(id) { if (typeof id !== 'number' || id <= 0) { throw new Error('ID is invalid, check again'); } return new Promise((resolve, reject) => { resolve({ id: id, username: 'someUser' }); }); } try { fetchUser('id1') .then(user => content += JSON.stringify(user.username)) .catch(err => error += err); } catch (er) { error += er } } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

Conclusion

Handling asynchronous tasks is one of the most common tasks in network programming. Javascript used async and await keywords to qualify basic functions for asynchronous functions. When we are downloading data from the web, or reading a large file that is not synchronous with our system, we can tell the compiler that please do not stop while it is working, it will do its work in the background. And when it is done, do the rest which is specified in the code. For that, the async and await keywords are the most commonly used features in javascript.


Advertisements